MaxFileSize 和甘蓝文件上传插件不工作的文件类型。为什么?

我使用 Blueimp jQuery 文件上传插件来上传文件。

我在上传没有问题,但选项 maxFileSizeacceptFileTypes不工作。

这是我的暗号:

$(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 + '%');
}
});
});
114949 次浏览

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.

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.

You could also use an extra function like:

    function checkFileType(filename, typeRegEx) {
if (filename.length < 4 || typeRegEx.length < 1) return false;
var filenameParts = filename.split('.');
if (filenameParts.length < 2) return false;
var fileExtension = filenameParts[filenameParts.length - 1];
return typeRegEx.test('.' + fileExtension);
}

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

This works for me in firefox

$('#fileupload').fileupload({


dataType: 'json',
//acceptFileTypes: /(\.|\/)(xml|pdf)$/i,
//maxFileSize: 15000000,


add: function (e, data) {
var uploadErrors = [];


var acceptFileTypes = /\/(pdf|xml)$/i;
if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('File type not accepted');
}


console.log(data.originalFiles[0]['size']) ;
if (data.originalFiles[0]['size'] > 5000000) {
uploadErrors.push('Filesize too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.context = $('<p/>').text('Uploading...').appendTo(document.body);
data.submit();
}


},
done: function (e, data) {
data.context.text('Success!.');
}
});

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

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);
});
});

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();
}
};

This worked for me in chrome, jquery.fileupload.js version is 5.42.3

     add: function(e, data) {
var uploadErrors = [];
var ext = data.originalFiles[0].name.split('.').pop().toLowerCase();
if($.inArray(ext, ['odt','docx']) == -1) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0].size > (2*1024*1024)) {//2 MB
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
.fileupload({
add: function (e, data) {
var attachmentValue = 3 * 1000 * 1024;
var totalNoOfFiles = data.originalFiles.length;
for (i = 0; i < data.originalFiles.length; i++) {
if (data.originalFiles[i]['size'] > attachmentValue) {
$attachmentsList.find('.uploading').remove();
$attachmentMessage.append("<li>" + 'Uploaded bytes exceeded the file size' + "</li>");
$attachmentMessage.show().fadeOut(10000, function () {
$attachmentMessage.html('');
});
data.originalFiles.splice(i, 1);
}
}
if (data.files[0]) {
$attachmentsList
.prepend('<li class="uploading" class="clearfix loading-content">' + data.files[0].name + '</li>');
}
data.submit();
}

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);
});
}
...
});

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.

  • You can also use the file extension to check for the filetype.
  • More simpler way would be to do something as given below inside add :

    add : function (e,data){
    var extension = data.originalFiles[0].name.substr(
    (data.originalFiles[0].name.lastIndexOf('.') +1) );
    switch(extension){
    case 'csv':
    case 'xls':
    case 'xlsx':
    data.url = <Your URL>;
    data.submit();
    break;
    default:
    alert("File type not accepted");
    break;
    }
    }
    

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();
},

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