MaxFileSize and acceptFileTypes in the blueimp file upload plugin do not work. What for?

I am using the Blueimp jQuery file upload plugin to upload files.

I had no problems loading, but the 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 + '%'); } }); }); 
+81
javascript jquery file-upload jquery-file-upload blueimp
Jul 03 '13 at 15:08
source share
15 answers

Had the same problem, and the weather forecaster said: " maxFileSize and acceptFileTypes are only supported by the user interface version " and provided (broken) to enable the _validate and _hasError methods.

Therefore, not knowing how to enable these 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 beginning 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 will notice that I added the filesize function there, because this will also work only in the user interface version.

Updated to get the previous problem suggested by @lopsided: added data.originalFiles[0]['type'].length and data.originalFiles[0]['size'].length in requests to make sure they exist and not are empty before error testing. If they do not exist, the error will not be shown, and it will rely only on error checking on the server side.

+131
Jul 14 '13 at 6:03
source share
+45
Nov 19 '13 at 16:15
source share

As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js and then jquery.fileupload-validate.js However, since I need to make some additional ajax calls when adding a file, I subscribe to the fileuploadadd event to make these calls. Regarding this use, the author of this plugin suggested the following

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

Adding additional event listeners using the bind method (or the jQuery 1.7+ method) is the preferred option for saving callback parameters using the jQuery file upload user interface version.

Alternatively, you can also just start processing in your callback, for example: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50

Using a combination of the two suggested options, the following code works fine 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); }); }); 
+10
May 03 '14 at 15:24
source share

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!.'); } }); 
+7
Dec 30 '14 at 5:48
source share

open the file called "jquery.fileupload-ui.js", you will see the code as follows:

  $.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 acceptFileTypes attribute, for example:

  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 will see that everything is in order! ~ you just take the attribute with the wrong place.

+3
Oct 10 '13 at 7:31
source share

If you have all the imported JS plugins in the correct order, but you still have problems, it seems that telling your own handler to “add” nerfs means the one from the * -validate.js plugin that usually resets all checks by calling data.process (). Therefore, to fix this, just do something similar 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); }); } ... }); 
+3
Feb 16 '16 at 20:12
source share

Checked / Valid example for:

  • multiple input files
  • for one or MULTIFUNCTION upload files - $.grep() to delete files from the array with errors
  • image and audio format
  • dynamic file types from string new RegExp()

Note: acceptFileTypes.test() - check the mime types, for an adio file such as .mp3 will be audio/mpeg - not just 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 
+1
Mar 24 '14 at 22:13
source share

Just an example event handler for the Add event. The singleFileUploads option is assumed to be enabled (by default). Learn more jQuery Download the documentation related to the add / fileuploadadd event. Inside the loop you can use both vars of this or the file . An example of getting the 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(); } }; 
+1
Feb 22 '15 at 23:31
source share

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(); } }, 
+1
Apr 22 '15 at 13:28
source share
 .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(); } 
+1
Oct. 15 '15 at 10:03
source share

You can also use an additional function, for example:

  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); } 
0
Oct 29 '13 at 1:49 on
source share

You must enable jquery.fileupload-process.js and jquery.fileupload-validate.js for it to 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 triggered after a failed validation.

0
Jan 18 '17 at 17:53 on
source share
  • You can also use the file extension to check the file type.
  • An easier way would be to do something as indicated 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; } } 
0
Apr 20 '18 at 9:56
source share

if you have multiple files, you use a loop to check each 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
05 Sep '18 at 8:42
source share

In case someone searches for frequently supported formats on the 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
Jun 04 '19 at 6:57
source share



All Articles