javascript 如何在 DropzoneJS 中显示自定义错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23842742/
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
How to show a custom error message in DropzoneJS?
提问by Pars
I need to check if a file has a valid MIME type, if the file size is ok and if its dimensions are ok, then upload file.
我需要检查文件是否具有有效的 MIME 类型,文件大小是否正常以及尺寸是否正常,然后上传文件。
So when everything is OK, I can use:
所以当一切正常时,我可以使用:
complete: function(file){
// do something here.
}
but what if the size of file was invalid? In my PHP script I return an error message:
但是如果文件的大小无效怎么办?在我的 PHP 脚本中,我返回一条错误消息:
return json_encode(['error' => 'size is invalid']);
OR
或者
return Response::json(['error' => 'size is invalid'], 500 ];
// this is Laravel 4 syntax. returns a json array and 500 as status code.
but how can I handle that error
in DropzoneJS?
但是我如何error
在 DropzoneJS 中处理它?
I tried adding a second parameter to the complete()
function but it's not working.
我尝试向该complete()
函数添加第二个参数,但它不起作用。
complete: function(file, response){
console.log( response ); // this does not work.
}
回答by Vedant Terkar
To get the response after the file was submitted to server use this in DropzoneJS:
要在文件提交到服务器后获得响应,请在 DropzoneJS 中使用它:
success: function(file, response) {
alert(response);
}
And to validate the file before uploading it use this:
并在上传文件之前验证文件,请使用:
complete: function(file) {
if (file.size > 3.5*1024*1024) {
alert("File was Larger than 3.5Mb!");
return false;
}
if(!file.type.match('image.*')) {
alert("Upload Image Only!");
return false;
}
}
If your server is returning response
in JSON
, you'll need to use JSON.parse
before alert
ing it.
如果您的服务器返回response
in JSON
,则需要JSON.parse
在alert
ing之前使用它。
Hope it'll help you! Cheers! :)
希望能帮到你!干杯! :)
回答by dbr
Just to simplify what @amandasantanati said so you don't click around:
只是为了简化@amandasantanati 所说的,这样你就不会四处点击:
Don't do complete: ...
but instead:
不要做complete: ...
,而是:
init: function()
{
this.on("complete", function(file) {
if (file.size > 3.5*1024*1024) {
this.removeFile(file);
alert('file too big');
return false;
}
if(!file.type.match('image.*')) {
this.removeFile(file);
alert('Not an image')
return false;
}
});
},