maxFileSize and acceptFileTypes in blueimp file up

2019-01-12 16:17发布

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

I had no problem in uploading but the option maxFileSize and acceptFileTypes do not work.

This is my code:

$(document).ready(function () {
    'use strict';

    $('#fileupload').fileupload({
        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 + '%');
        }
    });
});

14条回答
Emotional °昔
2楼-- · 2019-01-12 16:53

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.

查看更多
迷人小祖宗
3楼-- · 2019-01-12 16:53

open the file named "jquery.fileupload-ui.js", you will see the code like this:

 $.widget('blueimp.fileupload', $.blueimp.fileupload, {

    options: {
        // By default, files added to the widget are uploaded as soon
        // as the user clicks on the start buttons. To enable automatic
        // uploads, set the following option to true:
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        autoUpload: false,
        // The ID of the upload template:
        uploadTemplateId: 'template-upload',
        // The ID of the download template:
        downloadTemplateId: 'template-download',
        。。。。

just add one line code --- the new attribute "acceptFileTypes",like this:

 options: {
        // By default, files added to the widget are uploaded as soon
        // as the user clicks on the start buttons. To enable automatic
        // uploads, set the following option to true:
        **acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,**
        autoUpload: false,
        // The ID of the upload template:
        uploadTemplateId: 'template-upload',
        // The ID of the download template:
        downloadTemplateId: 'template-d

now you'll see everything is allright!~ you just take the attribute with a wrong place.

查看更多
冷血范
4楼-- · 2019-01-12 16:53

Checked/Valid example for:

  • multiple file inputs
  • for one or MULTIPLE FILES upload - $.grep() to remove files from array with errors
  • image and audio format
  • dynamic file types from string by new RegExp()

Notice: acceptFileTypes.test() - check mime types, for adio file like .mp3 it will be audio/mpeg - not only extenstion. For all blueimp options: https://github.com/blueimp/jQuery-File-Upload/wiki/Options

$('input[type="file"]').each(function(i){

    // .form_files is my div/section of form for input file and progressbar
    var $progressbar = $(this).parents('.form_files:first').find('.progress-bar:first');

    var $image_format = 'jpg|jpeg|jpe|png|gif';
    var $audio_format = 'mp3|mpeg';
    var $all_formats = $image_format + '|' + $audio_format;

    var $image_size = 2;
    var $audio_size = 10;
    var mb = 1048576;

    $(this).fileupload({
        // ...
        singleFileUploads: false,   // << send all together, not single
        // ...
        add: function (e, data) {

            // array with all indexes of files with errors
            var error_uploads_indexes = [];

            // when add file - each file
            $.each(data.files, function(index, file) {

                // array for all errors
                var uploadErrors = [];


                // validate all formats first
                if($all_formats){

                    // check all formats first - before size
                    var acceptFileTypes = "(\.|\/)(" + $all_formats + ")$";
                    acceptFileTypes = new RegExp(acceptFileTypes, "i");

                    // when wrong format
                    if(data.files[index]['type'].length && !acceptFileTypes.test(data.files[index]['type'])) {
                        uploadErrors.push('Not an accepted file type');

                    }else{

                        // default size is image_size
                        var $my_size = $image_size;

                            // check audio format
                            var acceptFileTypes = "(\.|\/)(" + $audio_format + ")$";
                            acceptFileTypes = new RegExp(acceptFileTypes, "i");

                            // alert(data.files[index]['type']);
                            // alert(acceptFileTypes.test('audio/mpeg'));

                            // if is audio then size is audio_size
                            if(data.files[index]['type'].length && acceptFileTypes.test(data.files[index]['type'])) {
                                $my_size = $audio_size;
                            }

                        // check size
                        if(data.files[index]['size'] > $my_size * mb) {
                            uploadErrors.push('Filesize is too big');
                        };
                    };

                }; // << all_formats

                // when errors
                if(uploadErrors.length > 0) {
                    //  alert(uploadErrors.join("\n"));

                    // mark index of error file
                    error_uploads_indexes.push(index);
                    // alert error
                    alert(uploadErrors.join("\n"));

                };

            }); // << each


            // remove indexes (files) with error
            data.files = $.grep( data.files, function( n, i ) {
                return $.inArray(i, error_uploads_indexes) ==-1;
            });


            // if are files to upload
            if(data.files.length){
                // upload by ajax
                var jqXHR = data.submit().done(function (result, textStatus, jqXHR) {
                        //...
                     alert('done!') ;
                        // ...
                });
            } // 

        }, // << add
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressbar.css(
                'width',
                progress + '%'
                );
        }
    }); // << file_upload

    //          
}); // << each input file
查看更多
我命由我不由天
5楼-- · 2019-01-12 16:58

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.

查看更多
混吃等死
6楼-- · 2019-01-12 17:00

As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js and then jquery.fileupload-validate.js However as I need to perform some additional ajax calls while adding a file, I am subscribing to the fileuploadadd event to perform those calls. Regarding such a usage the author of this plugin suggested the following

Please have a look here: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options

Adding additional event listeners via bind (or on method with jQuery 1.7+) method is the preferred option to preserve callback settings by the jQuery File Upload UI version.

Alternatively, you can also simply start the processing in your own callback, like this: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50

Using the combination of the two suggested options, the following code works perfectly for me

$fileInput.fileupload({
    url: 'upload_url',
    type: 'POST',
    dataType: 'json',
    autoUpload: false,
    disableValidation: false,
    maxFileSize: 1024 * 1024,
    messages: {
        maxFileSize: 'File exceeds maximum allowed size of 1MB',
    }
});

$fileInput.on('fileuploadadd', function(evt, data) {
    var $this = $(this);
    var validation = data.process(function () {
        return $this.fileupload('process', data);
    });

    validation.done(function() {
        makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
            .done(function(resp) {
                data.formData = data.formData || {};
                data.formData.someData = resp.SomeData;
                data.submit();
        });
    });
    validation.fail(function(data) {
        console.log('Upload error: ' + data.files[0].error);
    });
});
查看更多
混吃等死
7楼-- · 2019-01-12 17:05

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);
   });
}
...
});
查看更多
登录 后发表回答