jQuery File Uploader Class

var MyFileUpload = null;

(($) => {

    MyFileUpload = class {

        constructor(selector, options = {}) {
            this.el = $(selector);

            if (this.el.length != 1 || this.el.attr('type') != 'file') {
                console.error('MyFileUpload['+selector+'] not found.');
                return;
            }

            this.input    = this.el[0];
            this.data     = new FormData();
            this.url      = options.url || this.el.data('url');
            this.name     = options.name || this.el.attr('name');
            this.response = null;

            if (this.url == undefined || this.name == undefined) {
                console.error('MyFileUpload['+selector+'] url or name is missing.');
                return;
            }

            this.processing = false;

            return this;
        }

        on(event, callback) {
            this.el.on(event, callback);

            return this;
        }

        async upload() {
            if (this.input.files.length == 0) {
                return this;
            }

            Array.from(this.input.files).forEach(file => {
                this.data.append(this.name, file, file.name);
            });

            this.processing = true;

            this.response = await new Promise((resolve, reject) => {
                $.ajax({
                    url: this.url,
                    method: 'post',
                    data: this.data,
                    processData: false,
                    contentType: false,
                }).then(r => {
                    this.flush();
                    resolve(r);
                }).catch(e => {
                    reject(e);
                }).always(() => {
                    this.processing = false;
                });
            });

            return this;
        }

        then(callback) {
            callback(this.response);

            return this;
        }

        flush() {
            this.input.value = null;
            this.data.delete(this.name);

            return this;
        }

    }

})(jQuery);
⚑ Tanggapan