blueimpfile upload插件中的maxFileSize和acceptFileTypes不起作用。 为什么?

我正在使用Blueimp jQueryfile upload插件来上传文件。

我没有上传的问题,但选项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 + '%'); } }); }); 

有同样的问题,blueimp家伙说:“ maxFileSize和acceptFileTypes只支持的UI版本 ”,并提供了一个(断开)的链接,以合并_validate和_hasError方法。

所以不知道如何把这些方法整合起来,而不用搞乱脚本,我写了这个小函数。 这似乎为我工作。

只需添加这个

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

在这里你的代码中显示的.fileupload选项的开始

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

你会注意到我也在里面添加了一个文件大小的函数,因为那也只能在UI版本中工作。

更新以获得@lopsidedbuild议的问题:添加data.originalFiles[0]['type'].lengthdata.originalFiles[0]['size'].length查询中的data.originalFiles[0]['size'].length以确保它们存在且不为空首先在testing错误之前。 如果它们不存在,则不会显示错误,只会依赖于服务器端的错误testing。

你应该包括jquery.fileupload-process.js和jquery.fileupload-validate.js使其工作。

正如在以前的答案build议,我们需要包括两个额外的文件 – jquery.fileupload-process.js然后jquery.fileupload-validate.js但是,因为我需要执行一些额外的Ajax调用,而添加一个文件,我订阅执行这些调用的fileuploadadd事件。 关于这个用法,这个插件的作者build议如下

请看看这里: https : //github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options

通过绑定(或使用jQuery 1.7+的方法)添加额外的事件侦听器是保留jQueryfile uploadUI版本的callback设置的首选方法。

或者,您也可以简单地在自己的callback中启动处理,如下所示: https : //github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50

使用两个build议的选项的组合,下面的代码完美地为我工作

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

这在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!.'); } }); 

如果你已经得到了所有JS导入的插件,并且顺序正确,但是你仍然有问题,似乎指定你自己的“add”处理器会从* -validate.js插件中调用,这通常会触发通过调用data.process()来closures所有的validation。 所以要解决它只是在你的“添加”事件处理程序中做这样的事情:

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

打开名为“jquery.fileupload-ui.js”的文件,你会看到这样的代码:

  $.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', 。。。。 

只需添加一行代码—新的属性“acceptFileTypes”,如下所示:

  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 

现在你会看到一切都是好的!〜你只是把属性放在一个错误的地方。

检查/有效的例子:

  • 多个文件input
  • 为一个或多个文件上传 – $.grep()从错误数组中删除文件
  • imageaudio格式
  • 来自string的dynamic文件types通过new RegExp()

注意: acceptFileTypes.test() – 检查MIMEtypes,对于像.mp3这样的adio文件,它将是audio/mpeg – 不仅是扩展。 对于所有blueimp选项: 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 

只是添加事件的事件处理程序的一个例子。 假定启用singleFileUploads选项(这是默认设置)。 阅读更多jQueryfile upload文档如何绑定add / fileuploadadd事件。 在内部循环中,您可以使用这个这个 文件 。 获取大小属性的示例: 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(); } }; 
 .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(); } 

你也可以使用一个额外的function,如:

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

这在Chrome中工作,jquery.fileupload.js版本是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(); } }, 

你应该包括jquery.fileupload-process.jsjquery.fileupload-validate.js使其工作。

然后…

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

在validation失败后启动processfailcallback。

Interesting Posts