Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow resubmission of file uploads after failure with Dropzone.js?

I have a file upload form that uses Dropzone.js to upload files to my server. A user can upload up to 5 fivles at once, but I have a unique condition I'm dealing with: if any single file errors out on the server end (over the maximum size, wrong mime-type, wrong file type, etc), I need none of the files to be added to my database. This is not a problem.

What I am having a problem with is the client side handling of it. Why is it when I get a response from the server, I can no longer upload files again by clicking "submit" (the element of which is bound to an event handler, as seen below)?

        Dropzone.options.uploadedFilesDropzone = {
              autoProcessQueue: false,
              maxFilesize: 1024, //MB
              addRemoveLinks: true,
              uploadMultiple: true,
              parallelUploads: 5,
              maxFiles: 5,
              init: function() {

                var uploadedFilesDropzone = this;

                $('#submit').on('click', function() {
                    uploadedFilesDropzone.processQueue();

                    uploadedFilesDropzone.on("successmultiple", function(files, response) {
                        // Handle the responseText here. For example, add the text to the preview element:
                        console.log(files);
                        console.log(response.errors[0]);
                        $.each(files, function(index, file) {
                            // no errors
                            if (response.errors[index].length == 0) {

                            } else {
                                file.previewElement.classList.add('dz-error');
                            }
                        })
                     });
                });
              }
        }
like image 414
marked-down Avatar asked Feb 09 '15 02:02

marked-down


1 Answers

Files are removed from the Dropzone queue once processQueue() is called. You can no longer upload the files by clicking submit because there are no files in the queue.

You need to add each file back into the queue after the response has been received.

If there is an error with the files server side it is best to set the status code of the response to something other than 200 so that you can override the Dropzone error listener.

    this.on("error", function(file, errorMessage) {
        $.each(dropZone.files, function(i, file) {
            file.status = Dropzone.QUEUED
        });

        $.each(message, function(i, item) {
            $("#dropzoneErrors .errors ul").append("<li>" + message[i] + "</li>")
        });
    });
like image 144
Diazole Avatar answered Nov 05 '22 15:11

Diazole