UploadDriver

class webix.UploadDriver()

Uploaddriver mixin

External references

Official documentation page.

Code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
webix.UploadDriver = {
    flash: {
        $render: function(render_config) {

            if (!window.swfobject)
                webix.require("legacy/swfobject.js", true); // sync loading

            var config = this._settings;
            config.swfId = (config.swfId||"webix_swf_"+webix.uid());

            this._getBox().innerHTML += "<div class='webix_upload_flash'><div id='"+config.swfId+"'></div></div>";
            this._upload_area = this._getBox().lastChild;

            // add swf object
            swfobject.embedSWF(webix.codebase+"/legacy/uploader.swf", config.swfId, "100%", "100%", "9", null, {
                    uploaderId: config.id,
                    ID: config.swfId,
                    enableLogs:(config.enableLogs?"1":""),
                    paramName:(config.inputName),
                    multiple:(config.multiple?"Y":"")
            }, {wmode:"transparent"});

            var v = swfobject.getFlashPlayerVersion();

            webix._event(this._viewobj, "click", webix.bind(function() {
                var now_date = new Date();
                if (now_date - (this._upload_timer_click||0)  > 250){
                    this.fileDialog();
                }
            }, this));

            this.files.attachEvent("onBeforeDelete", webix.bind(this._stop_file,this));
        },
        $applyFlash: function(name,params){
            return this[name].apply(this,params);
        },
        getSwfObject: function(){
            return swfobject.getObjectById(this._settings.swfId);
        },
        fileDialog:function(){
            if(this.getSwfObject())
                this.getSwfObject().showDialog();
        },
        send: function(id){
            if (typeof id == "function"){
                this._last_assigned_upload_callback = id;
                id = 0;
            }

            if (!id){
                var order = this.files.data.order;
                var complete = true;
                if (order.length)
                    for (var i=0; i<order.length; i++){
                        complete = this.send(order[i])&&complete;
                    }

                if (complete)
                    this._upload_complete();

                return;
            }
            var item = this.files.getItem(id);
            if (item.status !== 'client')
                return false;
            item.status = 'transfer';

            if(this.getSwfObject()){
                var url = this._get_active_url(item);
                var details = webix.extend(item.formData||{},this._settings.formData||{});
                this.getSwfObject().upload(id, url, details);
            }
            return true;

        },
        $beforeAddFileToQueue: function( id, name, size ){

            var type = name.split(".").pop();
            var format = this._format_size(size);
            return this.callEvent("onBeforeFileAdd", [{
                id: id,
                name:name,
                size:size,
                sizetext:format,
                type:type
            }]);
        },
        $addFileToQueue: function(id, name, size){
            if(this.files.exists(id))
                return false;
            if (!this._settings.multiple)
                this.files.clearAll();
            var type = name.split(".").pop();
            var format = this._format_size(size);
            var file_struct = {
                name:name,
                id: id,
                size:size,
                sizetext:format,
                type:type,
                status:"client"
            };
            this.files.add(file_struct);
            this.callEvent("onAfterFileAdd", [file_struct]);

            if (id && this._settings.autosend)
                this.send(id);
        },
        stopUpload: function(id){
            this._stop_file(id);
        },
        _stop_file: function(id) {
            var item = this.files.getItem(id);
            if(item.status == "transfer"){
                this.getSwfObject().uploadStop(id);
                item.status = "client";
            }
        },
        $onUploadComplete: function(){
            if(this._settings.autosend){
                this._upload_complete();
            }
        },
        $onUploadSuccess: function(id,name,response){
            var item = this.files.getItem(id);
            if(item){
                item.status = "server";
                item.progress = 100;
                if(response.text && (typeof response.text == "string")){


                    webix.DataDriver.json.toObject(response.text);

                    webix.extend(item,response,true);
                }
                this.callEvent("onFileUpload", [item,response]);
                this.callEvent("onChange", []);
                this.files.updateItem(id);
            }
        },
        $onUploadFail: function(id){
            var item = this.files.getItem(id);
            item.status = "error";
            delete item.percent;
            this.files.updateItem(id);
            this.callEvent("onFileUploadError", [item, ""]);
        }
    },
    html5: {
        $render: function(config) {
            if (this._upload_area){
                //firstChild is webix_el_box container, which have relative position
                //as result, file control is placed under the button and not in the top corner
                this._contentobj.firstChild.appendChild(this._upload_area);
                return;
            }
            this.files.attachEvent("onBeforeDelete", this._stop_file);

            var input_config =  {
                "type": "file",
                "class": "webix_hidden_upload",
                tabindex:-1
            };

            if (this._settings.accept)
                input_config.accept = this._settings.accept;

            if (this._settings.multiple)
                input_config.multiple = "true";

            if (this._settings.directory) {
                input_config.webkitdirectory = "true";
                input_config.mozdirectory = "true";
                input_config.directory = "true";
            }

            var f = webix.html.create("input", input_config);
            this._upload_area = this._contentobj.firstChild.appendChild(f);

            webix._event(this._viewobj, 'drop', webix.bind(function(e) {
                this._drop(e);
                webix.html.preventEvent(e);
            }, this));
            webix._event(f, 'change', webix.bind(function() {
                this._add_files(f.files);

                if (webix.env.isIE) {
                    var t = document.createElement("form");
                    t.appendChild(this._upload_area);
                    t.reset();
                    this._contentobj.firstChild.appendChild(f);
                } else
                    f.value = "";
            }, this));
            webix._event(this._viewobj, "click", webix.bind(function() {
                var now_date = new Date();
                if (now_date - (this._upload_timer_click || 0) > 250) {
                    this.fileDialog();
                }
            }, this));

            webix._event(this._viewobj, 'dragenter', webix.html.preventEvent);
            webix._event(this._viewobj, 'dragexit', webix.html.preventEvent);
            webix._event(this._viewobj, 'dragover', webix.html.preventEvent);
        },
        _directoryEntry: function(value) {
            return value.isDirectory;
        },
        _directoryDrop: function(item, state, path) {
            if (item.isFile){
                item.file(function(file){
                    state.addFile(file, null, null, { name : path+"/"+file.name });
                });
            } else if (item.isDirectory) {
                // Get folder contents
                var dirReader = item.createReader();
                dirReader.readEntries(function(entries){
                    for (var i = 0; i < entries.length; i++){
                        state._directoryDrop(entries[i], state, (path ? (path + "/") : "") + item.name);
                    }
                });
            }
        },
        // adding files by drag-n-drop
        _drop: function(e) {
            var files = e.dataTransfer.files;
            var items = e.dataTransfer.items;

            if (this.callEvent('onBeforeFileDrop', [files, e])) {
                for (var i = 0; i < items.length; i++) {
                    //https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry
                    var item = items[i];
                    if (this._settings.directory && item.webkitGetAsEntry){
                        item = item.webkitGetAsEntry();
                        if (item.isDirectory){
                            this._directoryDrop(item, this, "");
                            continue;
                        }
                    }
                    this.addFile(files[i]);
                }
            }
            this.callEvent("onAfterFileDrop", [files, e]);
        },
        fileDialog:function(context){
            this._upload_timer_click = new Date();
            this._last_file_context = context;
            var inputs = this._viewobj.getElementsByTagName("INPUT");
            inputs[inputs.length-1].click();
        },
        send: function(id){
            //alternative syntx send(callback)
            if (typeof id == "function"){
                this._last_assigned_upload_callback = id;
                id = 0;
            }

            if (!id){
                var order = this.files.data.order;
                var complete = true;

                if (order.length)
                    for (var i=0; i<order.length; i++)
                        complete = (!this.send(order[i])) && complete;

                if (complete)
                    this._upload_complete();

                return;
            }

            var item = this.files.getItem(id);
            if (item.status !== 'client') return false;

            webix.assert(this._settings.upload, "You need to define upload url for uploader component");
            item.status = 'transfer';

            var formData = new FormData();

            if (item.folder) {
                for (var i = 0; i < item.folder.length; i++){
                    formData.append(this.config.inputName + i, item.folder[i], item.folder[i].webkitRelativePath);
                }
            } else {
                formData.append(this.config.inputName, item.file, item.name);
                if (this._settings.directory)
                    formData.append(this.config.inputName+"_fullpath", item.name);
            }

            var headers = {};
            var details = webix.extend(item.formData||{},this._settings.formData||{});

            var xhr = new XMLHttpRequest();
            var url = this._get_active_url(item);
            if(webix.callEvent("onBeforeAjax",["POST", url, details, xhr, headers, formData])){
                for (var key in details)
                    formData.append(key, details[key]);

                item.xhr = xhr;

                xhr.upload.addEventListener('progress', webix.bind(function(e){ this.$updateProgress(id, e.loaded/e.total*100); }, this), false);
                xhr.onload = webix.bind(function(e){ if (!xhr.aborted) this._file_complete(id); }, this);
                xhr.open('POST', url, true);

                for (var key in headers)
                    xhr.setRequestHeader(key, headers[key]);

                xhr.send(formData);
            }

            this.$updateProgress(id, 0);
            return true;
        },


        _file_complete: function(id) {
            var item = this.files.getItem(id);
            if (item){
                var response = null;
                if(item.xhr.status < 400){
                    response = webix.DataDriver[this._settings.datatype||"json"].toObject(item.xhr.responseText);
                }
                if (!response || response.status == "error"){
                    item.status = "error";
                    delete item.percent;
                    this.files.updateItem(id);
                    this.callEvent("onFileUploadError", [item, response]);
                } else {
                    this._complete(id, response);
                }
                delete item.xhr;
            }
        },
        stopUpload: function(id){
            webix.bind(this._stop_file,this.files)(id);
        },
        _stop_file: function(id) {
            var item = this.getItem(id);
            if (typeof(item.xhr) !== 'undefined'){
                item.xhr.aborted = true;
                item.xhr.abort();
                delete item.xhr;
                item.status = "client";
            }
        }
    }
};