dropzone.js

Dropzonejs remove files without calling remove callback


I'm using Dropzonejs to upload files to use in my module. The way it works is you edit an item, you drag a file to the dropzone, the dropzone hides and you see a preview of the image. That preview is self-made and has a delete button to delete the image and nullify the column in the database.

To delete the files, the dropzone has a .on call for removedfile. This is put in a global function looking something like this (only with the important data for the question):

function createDropzone(removeCallback, id) {
    $('#' + id).dropzone({
        url: 'URL TO UPLOAD FILE',
        init: function() {
            var myDropzone = this;

            this.on('removedfile', function(file) {
                $.post('URL TO DELETE FILE', {file: file}, function(response) {
                    // handle delete
            } 
        },
    }
}

Now in this specific module when somebody uploads an image, it has to hide the dropzone element and show a custom preview element. However, if somebody wishes to delete the image, it has to remove the files from the dropzone AND run the click event when clicked on the delete icon by the custom preview.

The problem however is, if an image exists, it won't add the image to the dropzone and you will see the custom preview immediately. Thus, I cannot simply call the dropzone removeallfiles function, since the dropzone doesn't always contain the image. But when I call the removeallfiles function AND the event is called and an image is in the dropzone, it will try to remove the file twice.

Is there any way to remove all files from the dropzone without getting the removedfiles called?

(sorry if my explaination isn't well, it's still early in the morning, I can explain it better)


Solution

  • I was dumb, I had a check in the removeFiles callback already (in my original code) so that if a specific element doesn't exist, it won't execute the AJAX file.

    this.on('removedfile', function (file) {
        if (file.previewTemplate.children[6]) {
                // $.POST CODE HERE
        }
    }
    

    This element is created in the successmultiple event like this:

    previewTemplate.append('<input type="hidden" name="fileNames[]" value="' + ajaxResponse.filenames[i] + '">');
    previewTemplate.append('<input type="hidden" name="extensions[]" value="' + ajaxResponse.extensions[i] + '">');
    

    This way, when the element is removed, it won't go in the IF but still be removed from the dropzone. This way, you can remove all files from the dropzone without calling the remove file AJAX.