如何在DropzoneJS中显示自定义错误消息?

时间:2014-05-24 08:10:11

标签: javascript dropzone.js

我需要检查一个文件是否具有有效的MIME类型,如果文件大小正常并且其尺寸正常,则上传文件。

所以当一切正常时,我可以使用:

complete: function(file){
    // do something here.
}

但如果文件大小无效怎么办?在我的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.

但是如何在DropzoneJS中处理error

我尝试在complete()功能中添加第二个参数,但它无效。

complete: function(file, response){
    console.log( response ); // this does not work.
}

3 个答案:

答案 0 :(得分:7)

要在文件提交到服务器后获取响应,请在DropzoneJS中使用它:

success: function(file, response) {
  alert(response);
}

要在上传之前验证文件,请使用以下命令:

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

如果您的服务器在response返回JSON,则需要在JSON.parse之前使用alert

希望它能帮到你!干杯! :)

答案 1 :(得分:2)

只是为了简化@amandasantanati所说的内容,所以你不要点击:

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

答案 2 :(得分:1)

设置HTTP响应代码 http_response_code(415); //不支持的媒体类型 或http_response_code(415); //不可接受

    function showError($message)
    {
        http_response_code(415);
        die($message);
    }

enter image description here