How to Show a Custom Error Message in Dropzonejs?
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. So When Everything Is Ok, I Can Use...
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.
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:
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?
I tried adding a second parameter to the complete() function but it's not working.
complete: function(file, response){
console.log( response ); // this does not work.
}
4 Answers
To get the response after the file was submitted to server use this in 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 alerting it.
Hope it'll help you! Cheers! :)
Set the HTTP response code http_response_code(415); // Unsupported Media Type or http_response_code(415); // Not Acceptable
function showError($message)
{
http_response_code(415);
die($message);
}
Just to simplify what @amandasantanati said so you don't click around:
Don't do complete: ... but instead:
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;
}
});
},
it is always better to validate before upload, so use 'error' event like this:
myDropzone.on('error', function (file) {
if ((file.size / 1024 / 1024) > this.options.maxFilesize) {
this.removeAllFiles();
alert('error');
}
});
if you still want to handle this after upload, you can send the response from controller like:
<?php return Response::json(['error' => 'size is invalid'], 400 ]; ?>
and handle the response like:
myDropzone.on('error', function (file, response) {
if(typeof response =="object"){
alert(response.error);
}
});