Reinitialize/Reset dropzone after form is submitted
Asked Answered
V

7

12

I'm using the dropzone.js to upload image on ruby on rails .Here is my HTML code

<div class="row">
  <div class="col-md-12" id="drop-zone-container">
    <%= form_tag '/settlement_proofs', method: :post, class: 'dropzone form', id: 'media-dropzone' do %>
        <div class="fallback">
          <%= file_field_tag 'attachment', multiple: true%>
        </div>
    <% end %>
  </div>
</div>

and I initialized dropzone as

$("#media-dropzone").dropzone({
    acceptedFiles: pg.constants.ACCEPTED_FORMAT,
    maxFilesize: pg.constants.ATTACHMENT_MAX_FILE_SIZE, //In MB
    maxFiles: pg.constants.ATTACHMENT_MAX_SIZE,
    addRemoveLinks: true,
    removedfile: function (file) {
        if (file.xhr.responseText.length > 0) {
            var fileId = JSON.parse(file.xhr.responseText).id;
            $.ajax({
                url: pg.constants.url.SETTLEMENT_BASE_URL + fileId,
                method: 'DELETE',
                dataType: "json",
                success: function (result) {
                    $('#uploaded_attachment').val($("#uploaded_attachment").val().replace(result.id + ',', ""));
                    $('#settlement_proof_status span').fadeOut(0);
                    var _ref;
                    return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;

                },
                error: function () {
                    $('#settlement_proof_status').text(I18n.t('attachment_deletion_error')).fadeIn();
                }

            });
        }

    },
    init: function () {

        this.on("success", function (file, message) {
            debugger;
            appendContent(message.attachment.url, message.id);
        });

        this.on("error", function (file, message) {
            $('#settlement_proof_status span').text(message).fadeIn();
            var _ref;
            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
        });
        $('#settlement_invoice_submit_btn').click(function () {
            $("#new_settlement_invoice").submit();
        });
        $('#uploaded_attachment').change(function () {
            if (this.value.length == 0) {
                this.removeAllFiles();
            }
        });
    }
});

After I submit the form through AJAX, I need the dropzone field to reset with the default image.

Verbalize answered 13/7, 2015 at 10:6 Comment(2)
Possible duplicate of #21703026Munafo
In your provided link, user is using div instead of form to post the data.Here In my case I'm using formVerbalize
V
5

Finally, I solved the issue myself. At first I remove the form from its parents element.It removed the existing dropzone instance.Then I create the form using the jQuery and reinitialize the dropzone again. Here is my complete code

 // To reset dropzone before popup load
    var resetDropzone = function () {

        $('#drop-zone-container').empty();

        var $form = makeElement('form', {
            action: window.pg.constants.url.SETTLEMENT_BASE_URL,
            method: 'post',
            id: 'settlement-proof-form',
            class: 'dropzone'
        });

        $('#drop-zone-container').append($form);

        var settlmentProofDropZone;
        $("#settlement-proof-form").dropzone({
            acceptedFiles: pg.constants.ACCEPTED_FORMAT,
            maxFilesize: pg.constants.ATTACHMENT_MAX_FILE_SIZE, //In MB
            maxFiles: pg.constants.ATTACHMENT_MAX_SIZE,
            addRemoveLinks: true,
            removedfile: function (file) {
                if (file.xhr.responseText.length > 0) {
                    var fileId = JSON.parse(file.xhr.responseText).id;
                    $.ajax({
                        url: pg.constants.url.SETTLEMENT_BASE_URL + fileId,
                        method: 'DELETE',
                        dataType: "json",
                        success: function (result) {
                            $('#uploaded_attachment').val($("#uploaded_attachment").val().replace(result.id + ',', ""));
                            $('#settlement_proof_status span').fadeOut(0);
                            var _ref;
                            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;

                        },
                        error: function () {
                            $('#settlement_proof_status').text(I18n.t('attachment_deletion_error')).fadeIn();
                        }

                    });
                }

            },
            init: function () {
                settlmentProofDropZone = this;

                this.on("success", function (file, message) {
                    appendContent(message.attachment.url, message.id);
                });
            }
        });

    };

    function makeElement(element, options) {
        var $formField = document.createElement(element);
        $.each(options, function (key, value) {
            if (key === 'innerHTML') {
                $formField.innerHTML = value;
            }
            else {
                $formField.setAttribute(key, value);
            }
        });
        return $formField;
    }
});
Verbalize answered 14/7, 2015 at 11:3 Comment(0)
M
30
this.on("complete", function(file) { 
   this.removeAllFiles(true); 
})

write the above code in INIT function.

this removes all files in dropzone and RESETS the dropzone to initial state.

http://www.dropzonejs.com/#event-reset

Munafo answered 13/7, 2015 at 11:34 Comment(1)
I already tried it out.But I don't know why removeAllFiles(true) removes the file from server as wellVerbalize
S
8

I took an example from both Senug Nam Kim and J Santosh:

// Where .reset-dz is the class of a button
$('.reset-dz').on('click', function(e){
    var myDropzone = Dropzone.forElement("#user-post-submit");
    myDropzone.removeAllFiles(true); 
});
Saransk answered 23/3, 2018 at 1:31 Comment(0)
V
5

Finally, I solved the issue myself. At first I remove the form from its parents element.It removed the existing dropzone instance.Then I create the form using the jQuery and reinitialize the dropzone again. Here is my complete code

 // To reset dropzone before popup load
    var resetDropzone = function () {

        $('#drop-zone-container').empty();

        var $form = makeElement('form', {
            action: window.pg.constants.url.SETTLEMENT_BASE_URL,
            method: 'post',
            id: 'settlement-proof-form',
            class: 'dropzone'
        });

        $('#drop-zone-container').append($form);

        var settlmentProofDropZone;
        $("#settlement-proof-form").dropzone({
            acceptedFiles: pg.constants.ACCEPTED_FORMAT,
            maxFilesize: pg.constants.ATTACHMENT_MAX_FILE_SIZE, //In MB
            maxFiles: pg.constants.ATTACHMENT_MAX_SIZE,
            addRemoveLinks: true,
            removedfile: function (file) {
                if (file.xhr.responseText.length > 0) {
                    var fileId = JSON.parse(file.xhr.responseText).id;
                    $.ajax({
                        url: pg.constants.url.SETTLEMENT_BASE_URL + fileId,
                        method: 'DELETE',
                        dataType: "json",
                        success: function (result) {
                            $('#uploaded_attachment').val($("#uploaded_attachment").val().replace(result.id + ',', ""));
                            $('#settlement_proof_status span').fadeOut(0);
                            var _ref;
                            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;

                        },
                        error: function () {
                            $('#settlement_proof_status').text(I18n.t('attachment_deletion_error')).fadeIn();
                        }

                    });
                }

            },
            init: function () {
                settlmentProofDropZone = this;

                this.on("success", function (file, message) {
                    appendContent(message.attachment.url, message.id);
                });
            }
        });

    };

    function makeElement(element, options) {
        var $formField = document.createElement(element);
        $.each(options, function (key, value) {
            if (key === 'innerHTML') {
                $formField.innerHTML = value;
            }
            else {
                $formField.setAttribute(key, value);
            }
        });
        return $formField;
    }
});
Verbalize answered 14/7, 2015 at 11:3 Comment(0)
K
5

Try this:

//DropZone Initiation Section
init: function() {
    this.on('success', function(file, json) {
    });

    this.on('addedfile', function(file) {
    });

    this.on('drop', function(file) {
    });

    this.on('removedfile', function(file) {
    });

    this.on('complete', function(file) {
    });

    this.on('error', function(file) {
    });

    this.on('resetFiles', function() {
        if(this.files.length != 0){
            for(i=0; i<this.files.length; i++){
                this.files[i].previewElement.remove();
            }
            this.files.length = 0;
        }
    });
}

function JS_ClearDropZone() {
    //DropZone Object Get
    var objDZ = Dropzone.forElement("div#objDropzone");
    //"resetFiles" Event Call
    objDZ.emit("resetFiles");
}
Kevon answered 18/10, 2016 at 14:25 Comment(0)
P
4

Every answer here is incredibly complicated. I have a dropzone in a modal with some ajax to draw the uploaded/complete file on the page. If the user adds ANOTHER image to the gallery, I wanted to reset the dropzone in that modal without refreshing the page. The answer? See my solution here https://mcmap.net/q/909461/-how-can-i-reset-the-dropzone-in-this-code

Pitchblack answered 21/7, 2017 at 21:53 Comment(0)
S
2

Every Solution here is not for React, Any one can explain how it can we done with React Here is the code to remove files after upload in react

...
...


const initCallback = (dropzone) => {
    myDropzone = dropzone
  }

const eventHandlers = {
  init: initCallback,
  queuecomplete: () => {
    if (myDropzone && clearDropzone) {
      myDropzone.removeAllFiles()
    }
  }
}

....
...
Seventeenth answered 21/8, 2020 at 14:8 Comment(1)
It works on Web as well.Gallicanism
M
1

A simple solution built on script. For version 5.4.0

  1. Add it in you script what connect dropzone.js

$('button#submit_button').click(function () { $('.dz-preview').empty(); $('.dz-message').show(); });

  1. And in dropzone.js add line >>> $('.dz-message').hide();

    before return _this3.updateTotalUploadProgress(); (line 1277)

this.on("uploadprogress", function () { $('.dz-message').hide(); return _this3.updateTotalUploadProgress(); });

Milks answered 21/1, 2019 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.