maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

前端 未结 15 902
深忆病人
深忆病人 2020-12-07 08:34

I\'m using Blueimp jQuery file upload plugin for upload files.

I had no problem in uploading but the option maxFileSize and acceptFileTypes

相关标签:
15条回答
  • 2020-12-07 08:48

    You should include jquery.fileupload-process.js and jquery.fileupload-validate.js to make it work.

    Then...

    $(this).fileupload({
        // ...
        processfail: function (e, data) {
            data.files.forEach(function(file){
                if (file.error) {
                    self.$errorMessage.html(file.error);
                    return false;
                }
            });
        },
    //...
    }
    

    processfail callback is launched after a validation fail.

    0 讨论(0)
  • 2020-12-07 08:50

    In case anyone looking for commonly supported formats by server

    3g2|3gp|3gp2|3gpp|aac|aaf|aca|accdb|accde|accdt|acx|adt|adts|afm|ai|aif|aifc|aiff|appcache|application|art|asd|asf|asi|asm|asr|asx|atom|au|avi|axs|bas|bcpio|bin|bmp|c|cab|calx|cat|cdf|chm|class|clp|cmx|cnf|cod|cpio|cpp|crd|crl|crt|csh|css|csv|cur|dcr|deploy|der|dib|dir|disco|dll|dllconfig|dlm|doc|docm|docx|dot|dotm|dotx|dsp|dtd|dvi|dvr-ms|dwf|dwp|dxr|eml|emz|eot|eps|esd|etx|evy|exe|execonfig|fdf|fif|fla|flr|flv|gif|gtar|gz|h|hdf|hdml|hhc|hhk|hhp|hlp|hqx|hta|htc|htm|html|htt|hxt|ico|ics|ief|iii|inf|ins|isp|IVF|jar|java|jck|jcz|jfif|jpb|jpe|jpeg|jpg|js|json|jsonld|jsx|latex|less|lit|lpk|lsf|lsx|lzh|m13|m14|m1v|m2ts|m3u|m4a|m4v|man|manifest|map|mdb|mdp|me|mht|mhtml|mid|midi|mix|mmf|mno|mny|mov|movie|mp2|mp3|mp4|mp4v|mpa|mpe|mpeg|mpg|mpp|mpv2|ms|msi|mso|mvb|mvc|nc|nsc|nws|ocx|oda|odc|ods|oga|ogg|ogv|one|onea|onepkg|onetmp|onetoc|onetoc2|osdx|otf|p10|p12|p7b|p7c|p7m|p7r|p7s|pbm|pcx|pcz|pdf|pfb|pfm|pfx|pgm|pko|pma|pmc|pml|pmr|pmw|png|pnm|pnz|pot|potm|potx|ppam|ppm|pps|ppsm|ppsx|ppt|pptm|pptx|prf|prm|prx|ps|psd|psm|psp|pub|qt|qtl|qxd|ra|ram|rar|ras|rf|rgb|rm|rmi|roff|rpm|rtf|rtx|scd|sct|sea|setpay|setreg|sgml|sh|shar|sit|sldm|sldx|smd|smi|smx|smz|snd|snp|spc|spl|spx|src|ssm|sst|stl|sv4cpio|sv4crc|svg|svgz|swf|t|tar|tcl|tex|texi|texinfo|tgz|thmx|thn|tif|tiff|toc|tr|trm|ts|tsv|ttf|tts|txt|u32|uls|ustar|vbs|vcf|vcs|vdx|vml|vsd|vss|vst|vsto|vsw|vsx|vtx|wav|wax|wbmp|wcm|wdb|webm|wks|wm|wma|wmd|wmf|wml|wmlc|wmls|wmlsc|wmp|wmv|wmx|wmz|woff|woff2|wps|wri|wrl|wrz|wsdl|wtv|wvx|x|xaf|xaml|xap|xbap|xbm|xdr|xht|xhtml|xla|xlam|xlc|xlm|xls|xlsb|xlsm|xlsx|xlt|xltm|xltx|xlw|xml|xof|xpm|xps|xsd|xsf|xsl|xslt|xsn|xtp|xwd|z|zip
    
    0 讨论(0)
  • 2020-12-07 08:54

    if you have multiple file, you use a loop to verify each of the file format, something like this

    add: function(e, data) {
            data.url = 'xx/';
            var uploadErrors = [];
             var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
            console.log(data.originalFiles);
            for (var i = 0; i < data.originalFiles.length; i++) {
                if(data.originalFiles[i]['type'].length && !acceptFileTypes.test(data.originalFiles[i]['type'])) {
                        uploadErrors.push('Not an accepted file type');
                        data.originalFiles
                    }
                    if(data.originalFiles[i]['size'].length && data.originalFiles[i]['size'] > 5000000) {
                        uploadErrors.push('Filesize is too big');
                    }
                    if(uploadErrors.length > 0) {
    
                          alert(uploadErrors.join("\n"));
                    }
            }
            data.submit();
          },
    
    0 讨论(0)
  • 2020-12-07 08:57

    Just an example of event handler for Add event. Assumes that singleFileUploads option is enabled (which is the default). Read more jQuery File Upload documentation how to bound with add/fileuploadadd event. Inside loop you can use both vars this or file. An example of getting size property: this['size'] or file.size.

        /**
         * Handles Add event
         */
        base.eventAdd = function(e, data) {
    
            var errs = [];
            var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i;
            var maxFileSize = 5000000;
    
            // Validate file
            $.each(data.files, function(index, file) {
                if (file.type.length && !acceptFileTypes.test(file.type)) {
                    errs.push('Selected file "' + file.name + '" is not alloawed. Invalid file type.');
                }
                if (this['size'] > maxFileSize) {
                    errs.push('Selected file "' + file.name + '" is too big, ' + parseInt(file.size / 1024 / 1024) + 'M.. File should be smaller than ' + parseInt(maxFileSize / 1024 / 1024) + 'M.');
                }
            });
    
            // Output errors or submit data
            if (errs.length > 0) {
                alert('An error occured. ' + errs.join(" "));
            } else {
                data.submit();
            }
        };
    
    0 讨论(0)
  • 2020-12-07 08:58

    Had the same problem, and the blueimp guy says "maxFileSize and acceptFileTypes are only supported by the UI version" and has provided a (broken) link to incorporate the _validate and _hasError methods.

    So without knowing how to incorporate those methods without messing up the script I wrote this little function. It seems to work for me.

    Just add this

    add: function(e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
            if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }
            if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                uploadErrors.push('Filesize is too big');
            }
            if(uploadErrors.length > 0) {
                alert(uploadErrors.join("\n"));
            } else {
                data.submit();
            }
    },
    

    at the start of the .fileupload options as shown in your code here

    $(document).ready(function () {
        'use strict';
    
        $('#fileupload').fileupload({
            add: function(e, data) {
                    var uploadErrors = [];
                    var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                    if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                        uploadErrors.push('Not an accepted file type');
                    }
                    if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                        uploadErrors.push('Filesize is too big');
                    }
                    if(uploadErrors.length > 0) {
                        alert(uploadErrors.join("\n"));
                    } else {
                        data.submit();
                    }
            },
            dataType: 'json',
            autoUpload: false,
            // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            // maxFileSize: 5000000,
            done: function (e, data) {
                $.each(data.result.files, function (index, file) {
                    $('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
                    .appendTo('#div_files');
                });
            },
            fail: function (e, data) {
                $.each(data.messages, function (index, error) {
                    $('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
                    .appendTo('#div_files');
                });
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
    
                $('#progress .bar').css('width', progress + '%');
            }
        });
    });
    

    You'll notice I added a filesize function in there as well because that will also only work in the UI version.

    Updated to get past issue suggested by @lopsided: Added data.originalFiles[0]['type'].length and data.originalFiles[0]['size'].length in the queries to make sure they exist and are not empty first before testing for errors. If they don't exist, no error will be shown and it will only rely on your server side error testing.

    0 讨论(0)
  • 2020-12-07 08:58

    If you've got all the plugin JS's imported and in the correct order, but you're still having issues, it seems that specifying your own "add" handler nerfs the one from the *-validate.js plugin, which normally would fire off all the validation by calling data.process(). So to fix it just do something like this in your "add" event handler:

    $('#whatever').fileupload({
    ...
    add: function(e, data) {
       var $this = $(this);
       data.process(function() {
          return $this.fileupload('process', data);
       }).done(function(){
          //do success stuff
          data.submit(); <-- fire off the upload to the server
       }).fail(function() {
          alert(data.files[0].error);
       });
    }
    ...
    });
    
    0 讨论(0)
提交回复
热议问题