Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropzone.js retry if ajax failed

I'm using dropzone.js to upload certain files to my server. I have the problem that sometimes the server isn't able to keep up with the connections and refuses some uploads so they will fail and get marked red with an x. I would like to automaticaly retry after a certain amount of time or at least give the user the ability to restart it manually.

Is there an implemented feature in dropzone.js, an easy enough way to implement it for myself or is there a better tool to do those kinda uploads via drag/drop, preview, ajax, etc...?

like image 241
Lukas E. Avatar asked Oct 02 '22 05:10

Lukas E.


2 Answers

My solution is without changing the Dropzone library and only 4 lines long. I try the file upload two times because the first failed request sets a new cookie based CSRF token:

var isFirstTry = true;

myDropzone = new Dropzone(document.body, {
    init: function() {
        this.on("sending", function(file, xhr, formData) {
            xhr.setRequestHeader("X-CSRF", Cookies.get('CSRF'));
        });
    },
    error: function(file, errorMessage, xhr){
        if (errorMessage && errorMessage.status === 405 && file && isFirstTry) {
            isFirstTry = false;


            //remove item from preview
            this.removeFile(file)

            //duplicate File objet
            new File([file], file.name, { type: file.type });




            this.uploadFile(file);
        }
    },
    // other configs
});

After dropzone error event, dropzone fires complete event no matter what is the result. On complete dropzone set the status element to be complete. This hide the progress bar. To prevent this behavior, copy the File object. This prevent complete hook to handle the new preview element.

like image 57
Marc Avatar answered Oct 12 '22 13:10

Marc


One small modification to dropzone.js is required to make things look pretty but otherwise its just a directive.
My dropzone now retries (infinitely, but I'll fix that later) until it succeeds. A little more work is required to reset the progress bars but this should be enough to get you somewhere (if you still care about this).

The edit to dropzone.js is (in the beautified version):

                    success: function(file) {
                    file.previewElement.classList.remove("dz-error");
                    return file.previewElement.classList.add("dz-success");
                }

Where I've added the remove line. This changes Xs to ticks when a file successfully uploads.
The angular directive follows:

.directive('dropZone', function($rootScope) {
        return function ($scope, element, attr) {
            var myDropZone = element.dropzone({
                url: "api/ImageUpload",
                maxFilesize: 100,
                paramName: "uploadfile",
                maxThumbnailFilesize: 5,
                autoProcessQueue: false,
                parallelUploads: 99999,
                uploadMultiple: false,
                // this is my identifier so my backend can index the images together
                params: {identifier: $scope.identifier},
                // I seem to need to do this when a file is added, otherwise it doesn't update
                init: function(){this.on("addedfile", function(file){$rootScope.$digest();})}
            });
            // grabbing the dropzone object and putting it somewhere the controller can reach it
            $scope.dropZone = myDropZone.context.dropzone;
            // what we use to work out if we're _really_ complete
            $scope.errors = [];
            // here is our retry mechanism
            myDropZone.context.dropzone.addEventListener("error", function(file,errorMessage,xhr)
            {
                // log our failure so we don't accidentally complete
                $scope.errors.push(file.name);
                // retry!
                myDropZone.context.dropzone.uploadFile(file);
            });
            myDropZone.context.dropzone.addEventListener("success", function(file,errorMessage,xhr)
            {
               // remove from the error list once "success" (_not_ "complete")          
               $scope.errors.splice($scope.errors.indexOf(file.name), 1);
            });
             // this gets called multiple times because of our "retry"  
            myDropZone.context.dropzone.addEventListener("queuecomplete", function()
            {
                 // if we're here AND have no errors we're done
                if($scope.errors.length == 0)
                {
                      // this is my callback to the controller to state we're all done
                    $scope.uploadComplete();
                }
            });
        };
    })

not sure if all that myDropZone.context.dropZone stuff is necessary, I kinda suck at javascript and spend a lot of my time console.logging() objects and examining them in the debugger. This is where I found the dropzone component, perhaps there is an easier way?

like image 21
Quibblesome Avatar answered Oct 12 '22 13:10

Quibblesome