我正在使用Blueimp jQuery文件上传插件上传文件。
我上传时没有问题,但选项maxFileSize
和acceptFileTypes
不起作用。
这是我的代码:
$(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 + '%');
}
});
});
答案 0 :(得分:131)
有同样的问题,并且blueimp的人说“maxFileSize and acceptFileTypes are only supported by the UI version”,并提供了一个(损坏的)链接来合并_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 + '%');
}
});
});
你会注意到我在那里添加了一个filesize函数,因为它也只能在UI版本中使用。
已更新以获取@lopsided建议的过去问题:在查询中添加data.originalFiles[0]['type'].length
和data.originalFiles[0]['size'].length
以确保它们存在且在测试错误之前不是空的。如果它们不存在,则不会显示任何错误,只会依赖于服务器端错误测试。
答案 1 :(得分:45)
答案 2 :(得分:10)
正如在前面的回答中所建议的那样,我们需要包含两个额外的文件 - jquery.fileupload-process.js
然后jquery.fileupload-validate.js
但是因为我需要在添加文件时执行一些额外的ajax调用,所以我订阅了fileuploadadd
事件来执行这些调用。关于此类用法,此插件的作者suggested the following
请看这里: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options
通过bind(或使用jQuery 1.7+的方法)方法添加其他事件侦听器是通过jQuery文件上载UI版本保留回调设置的首选选项。
或者,您也可以在自己的回调中简单地开始处理,如下所示: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50
使用两个建议选项的组合,以下代码非常适合我
$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);
});
});
答案 3 :(得分:7)
这适用于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!.');
}
});
答案 4 :(得分:3)
打开名为“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
现在你会看到一切都很好!〜 你只需要把属性带到错误的地方。
答案 5 :(得分:3)
如果你已经按照正确的顺序导入了所有插件JS,但是你仍然遇到问题,那么似乎指定你自己的&#34;添加&#34;处理程序nerfs来自* -validate.js插件,它通常会通过调用data.process()来启动所有验证。所以要修复它,只需在你的&#34;添加&#34;事件处理程序:
$('#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);
});
}
...
});
答案 6 :(得分:1)
选中/有效示例:
$.grep()
从数组中删除有错误的文件image
和audio
格式new RegExp()
注意:acceptFileTypes.test()
- 检查mime类型,对于像.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
答案 7 :(得分:1)
仅为Add事件的事件处理程序示例。假设启用了singleFileUploads选项(这是默认选项)。阅读更多jQuery文件上载文档如何绑定add / fileuploadadd事件。在内部循环中,您可以使用此或文件这些变量。获取尺寸属性的示例:此[&#39;尺寸&#39;] 或 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();
}
};
答案 8 :(得分:1)
这在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();
}
},
答案 9 :(得分:1)
.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();
}
答案 10 :(得分:0)
您还可以使用额外的功能,如:
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);
}
答案 11 :(得分:0)
您应该包含 jquery.fileupload-process.js 和 jquery.fileupload-validate.js 以使其正常工作。
则...
$(this).fileupload({
// ...
processfail: function (e, data) {
data.files.forEach(function(file){
if (file.error) {
self.$errorMessage.html(file.error);
return false;
}
});
},
//...
}
验证失败后启动processfail 回调。
答案 12 :(得分:0)
更简单的方法是在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;
}
}
答案 13 :(得分:0)
如果您有多个文件,则可以使用循环来验证每种文件格式,诸如此类
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();
},
答案 14 :(得分:0)
万一有人在寻找服务器支持的常用格式
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