ivan-novakov / extjs-upload-widget

File upload widget for ExtJS v4
80 stars 42 forks source link

client side file size check / timeout support / small cleanups #20

Open middlebrain opened 10 years ago

middlebrain commented 10 years ago

While playing with the FormDataUploader I have seen that it was easy to implement client side file size checking and timeout support. I don't know if this is the most elegant solution, but it seems to work on current Firefox/Chrome (Linux) and on IE 10/11.

Feel free to accept or reject my small contribution.

--- lib/upload/uploader/FormDataUploader.js.orig    2013-11-05 10:06:41.000000000 +0100
+++ lib/upload/uploader/FormDataUploader.js 2013-12-02 15:57:32.347430530 +0100
@@ -5,9 +5,10 @@
 Ext.define('Ext.ux.upload.uploader.FormDataUploader', {
     extend : 'Ext.ux.upload.uploader.AbstractXhrUploader',

-    requires : [
-        'Ext.ux.upload.data.Connection'
-    ],
+    // Is not needed by this uploader implementation
+    // requires : [
+    //     'Ext.ux.upload.data.Connection'
+    // ],

     method : 'POST',
     xhr : null,
@@ -29,6 +30,18 @@
     },

     uploadItem : function(item) {
+        // Client side file size check
+        if (item.getSize() > this.maxFileSize) {
+            var info = {
+                success: false,
+                message: 'File too big',
+                response: null
+            };
+
+            this.fireEvent('uploadfailure', item, info);
+            return;
+        }
+
         var file = item.getFileApiObject();

         item.setUploading();
@@ -53,6 +66,15 @@
         xhr.addEventListener('loadend', loadendhandler, true);
         xhr.upload.addEventListener("progress", progresshandler, true);

+        xhr.timeout = this.timeout;
+
+        var timeouthandler = Ext.Function.bind(this.onTimeOut, this, [
+                item
+            ], true);
+
+        // the third parameter must be false. If true, then IE10/11 ignores the timeout
+        xhr.addEventListener('timeout', timeouthandler, false);
+
         xhr.send(formData);
     },

@@ -68,8 +90,7 @@
      * 
      * A placeholder for the abort procedure.
      */
-    abortXhr : function() {
-    },
+    abortXhr : Ext.emptyFn,

     onLoadEnd : function(event, item) {
         var response = event.target;
@@ -79,5 +100,9 @@
         }

         return this.onUploadSuccess(response, null, item);
+    },
+
+    onTimeOut : function(event, item) {
+        event.target.timedOut = true;
     }
 });
\ No newline at end of file
ivan-novakov commented 10 years ago

Thanks for the suggestion! I pushed a quick implementation of max file size checking to the devel branch, so you can test it. I'll add the timeout later :).

middlebrain commented 10 years ago

I have tested your (match better) size checking implementation with all uploaders and have no problems found so far.