Jquery 文件上传插件:如何在添加时验证文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15549094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery file upload plugin: how to validate files on add?
提问by cetver
$('#fileupload')
.fileupload({
acceptFileTypes: /(\.|\/)(jpg)$/i
})
.on('fileuploadadd', function (e, data) {
console.log(data.files.valid); //undefined
setTimeout(function () {
console.log(data.files.valid); //true or false
}, 500);
})
;
jsFiddle
How to get boolean value of property data.files.valid
without timeout ?
jsFiddle
如何在data.files.valid
没有超时的情况下获取属性的布尔值?
回答by bfncs
I needed to do validation with a current version of the plugin (5.39.1) and this works for me:
我需要使用插件的当前版本 (5.39.1) 进行验证,这对我有用:
Be sure to include jquery.fileupload-process.js
and jquery.fileupload-validate.js
in this order afterjquery.fileupload.js
and beforeyour initializing script.
确保在初始化脚本之后和之前包含jquery.fileupload-process.js
和jquery.fileupload-validate.js
按此顺序。jquery.fileupload.js
In your initializing script add the validation options and check validation in the fileuploadprocessalways
callback:
在您的初始化脚本中添加验证选项并在fileuploadprocessalways
回调中检查验证:
$('.fileinput').fileupload({
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// The maximum allowed file size in bytes:
maxFileSize: 10000000, // 10 MB
// The minimum allowed file size in bytes:
minFileSize: undefined, // No minimal file size
// The limit of files to be uploaded:
maxNumberOfFiles: 10
}).on('fileuploadprocessalways', function (e, data) {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
// there was an error, do something about it
console.log(currentFile.error);
}
});
All validations are optional, just don't leave the ones you don't need undefined
.
所有验证都是可选的,只是不要留下您不需要的验证undefined
。
回答by jszobody
Here is what you want to do:
这是您想要执行的操作:
$('#fileupload')
.fileupload({
acceptFileTypes: /(\.|\/)(jpg)$/i
})
.bind('fileuploadadded', function (e, data) {
console.log(data.files.valid);
});
The core jquery.fileupload.js file is adding your files and triggering the "fileuploadadd" event, but that's beforethe files are validated.
核心 jquery.fileupload.js 文件正在添加您的文件并触发“fileuploadadd”事件,但那是在验证文件之前。
The file jquery.fileupload-ui.js is doing the validation after the files are added, and triggering another "fileuploadadded" event once that's done.
文件 jquery.fileupload-ui.js 在添加文件后进行验证,并在完成后触发另一个“fileupload added”事件。
Change the event, and you're all set.
更改事件,一切就绪。
Please Note:
请注意:
This answer was valid and working as of March 2013 when it was posted. It appears that this upload plugin has changed since then. That means there is a new problem, and you should post a new question (or search to see if someone already has) rather than downvote this one!
该答案在 2013 年 3 月发布时有效且有效。从那时起,这个上传插件似乎发生了变化。这意味着有一个新问题,你应该发布一个新问题(或搜索看看是否有人已经有了),而不是对这个问题投反对票!
回答by Raphael Villas Boas
This is what I did and it worked for me for newer versions: I created one validation per type of file and its size.
这就是我所做的,它适用于较新的版本:我为每种类型的文件及其大小创建了一个验证。
$("#fileUploadArea").fileupload({
dataType: 'json',
url:'${upload}',
multiple:true,
autoSubmit:false,
maxNumberOfFiles: Number('${quantidadeMaximaArquivosUpload}'),
dynamicFormData: function()
{
var data ={
idEntidadeEmpresarial: $('#idEntidadeEmpresarial').val(),
idDominioFamilia: $('#idDominioFamilia').val(),
idSubgrupo: $('select[id^="subgrupo_').map(function(){return $(this).val();}).get(),
descricao: $('#descricao').val(),
validade: $('#validade').val()
}
return data;
},
headers: {
Accept: "application/json"
},
accept: 'application/json',
imageMaxWidth: 800,
imageMaxHeight: 800,
imageCrop: true ,
stop: function(){
$.unblockUI();
if($('#fechar').is(":checked")){
window.close();
}else{
$('select[id^="subgrupo_').each(function(){
$(this).val('');
$(this).trigger("chosen:updated");
})
$('#validade').val('');
$('#descricao').val('');
$('#sucesso').html('');
$('#sucesso').append('<p><spring:message code="upload.sucesso"/>');
$('#sucesso').show();
}
},
error: function(files,status,errMsg)
{
$('#erro').html('');
$('#erro').append('<p>'+errMsg+'</p>');
$('#erro').show();
},
acceptFileTypes : ${listaExtensaoPermitidas}
}).on('fileuploadprocessalways', function (e, data) {
var currentFile = data.files[data.index];
var tamanho = currentFile.size;
var extensao = currentFile.name.substring(currentFile.name.lastIndexOf(".") +1,currentFile.name.length);
if(hashExtensao.get(extensao.toUpperCase()) < tamanho){
alert("file type max size "+hashExtensao.get(extensao.toUpperCase());
data.abort();
}
});
回答by Dhruvil Amin
I think it can be possible using add method.
我认为可以使用 add 方法。
var fileUploadInit = function() {
$("#file-upload-form").fileupload({
dataType: "json",
url: url,
add: function (e, data){
if(validatefunction(data)){
data.submit();
} else {
return false;
}
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#upload-progress').css('width',progress + '%');
},
done: function(e, data) {
debugger
},
processfail: function(e, data){
debugger
}
})
}
var validatefunction = function(data){
// Do validation here. Return true if everything is correct else return false
}
回答by Tomasz
This is what you want to do with the newer version of the plugin (9.11.2):
Include this files:
- jquery.ui.widget.js
- jquery.iframe-transport.js
- jquery.fileupload.js
- jquery.fileupload-process.js
- jquery.fileupload-validate.js
这就是您想要使用较新版本的插件 (9.11.2) 执行的操作:包括以下文件:
-jquery.ui.widget.js
-jquery.iframe-transport.js
-jquery.fileupload.js
-jquery.fileupload -process.js
- jquery.fileupload-validate.js
$('#fileupload')
.fileupload({
acceptFileTypes: /(\.|\/)(jpg)$/i
})
.on('fileuploadadd', function (e, data) {
console.log('validation object not available at this point. Do not do submit here');
})
.on('fileuploadprocessalways', function (e, data) {
console.log(data.files.error);//true if error
console.log(data.files[0].error);//error message
if(!data.files.error) data.submit(); //do submission here
});
回答by Nis
Well, the answer by @jszbody is the perfect answer.
好吧,@jszbody 的答案是完美的答案。
However like myself in case if anyone lands here looking for solution to similar problem where user wants know if the file is not added correctly.
但是,就像我自己一样,以防万一有人在这里寻找类似问题的解决方案,用户希望知道文件是否未正确添加。
blueimp jquery-file-upload Doesn't throw error on unsuccessful add