Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke an error from server response (JSON) in Dropzone JS?

I have an uploader which rejects users' upload when they exceed their quota. The response is in JSON and it is as follow:

{msg: "Upload limit reached", status: "error", code: "403"}

The Dropzone JS options is as follow:

Dropzone.options.uploadDropzone = {
    paramName: "file1", 
    maxFilesize: 200, 
    maxThumbnailFilesize: 10,
    success: function(file, response){
      ????
  }
};

What should I do with the response in success to show an error to my users in the uploader?

like image 985
MK Yung Avatar asked Nov 29 '13 09:11

MK Yung


3 Answers

okay the following would work, just extract from the source:

success: function(file, response){
  if(response.code == 501){ // succeeded
    return file.previewElement.classList.add("dz-success"); // from source
  }else if (response.code == 403){  //  error
    // below is from the source code too
    var node, _i, _len, _ref, _results;
    var message = response.msg // modify it to your error message
    file.previewElement.classList.add("dz-error");
    _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      node = _ref[_i];
      _results.push(node.textContent = message);
    }
    return _results;
  }
}
like image 116
MK Yung Avatar answered Oct 21 '22 02:10

MK Yung


Dropzone has built in error detection. Just do this:

mydropzone = new Dropzone("#mydropzone",{
    url: "/dropzone",
    addRemoveLinks : true,
    maxFilesize: 2.0,
    maxFiles: 100,
    error: function(file, response) {
        if($.type(response) === "string")
            var message = response; //dropzone sends it's own error messages in string
        else
            var message = response.message;
        file.previewElement.classList.add("dz-error");
        _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            node = _ref[_i];
            _results.push(node.textContent = message);
        }
        return _results;
    }   
});
like image 40
spitz Avatar answered Oct 21 '22 00:10

spitz


You can do it like this:

success: function(file, response, action) {
    // PHP server response
    if(response == 'success') // Validate whatever you send from the server
    {
        this.defaultOptions.success(file);
    }
    else
    {
        this.defaultOptions.error(file, 'An error occurred!');  
    }
}
like image 42
CIRCLE Avatar answered Oct 21 '22 01:10

CIRCLE