How to remove the existing file dropzone?
Asked Answered
C

9

9

I have this sample:

link

CODE HTML:

<div class="dropzone dz-clickable" id="myDrop">
     <div class="dz-default dz-message" data-dz-message="">
          <span>Upload or drag patient photo here</span>
     </div>
</div>

CODE JS:

 Dropzone.autoDiscover = false;
 var myDropzone = new Dropzone("div#myDrop", {
   addRemoveLinks: true,
   url: "#",
   maxFiles: 1,
   init: function() {

     this.on("maxfilesexceeded", function(file) {
       alert("You are not allowed to chose more than 1 file!");
       this.removeFile(file);

     });

     this.on("addedfile", function(file) {
       myDropzone.options.removefile.call(myDropzone, mockFile);
       //  I want to delete an existing element
     });

   }
 });

 var fileName = $('#profilePicture').val();
 var mockFile = {
   name: fileName,
   size: 12345
 };
 myDropzone.options.addedfile.call(myDropzone, mockFile);
 myDropzone.options.thumbnail.call(myDropzone, mockFile, "https://lh3.googleusercontent.com/-eubcS91wUNg/AAAAAAAAAAI/AAAAAAAAAL0/iE1Hduvbbqc/photo.jpg?sz=104");

What I want to do is when the user uploads a file, then the existing one to be removed.

How can you do this correctly?

Thanks in advance!

Cark answered 8/3, 2016 at 8:25 Comment(2)
how about myDropzone.removeAllFiles() before upload another file?Mulligatawny
can you please edit my example?Cark
L
17

Try this method.

removedfile: function(file) {
            file.previewElement.remove();
}
Loan answered 23/5, 2017 at 8:6 Comment(0)
M
14

this is a working approach:

var currentFile = null;
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop", {
  addRemoveLinks: true,
  url: "#",
  maxFiles:1,
  init: function() {
    this.on("addedfile", function(file) {
      if (currentFile) {
        this.removeFile(currentFile);
      }
      currentFile = file;
    });
  }   
});
Mulligatawny answered 8/3, 2016 at 9:1 Comment(2)
yes but I want to replace the first image (the default is loaded)Cark
@Cark then just add currentFile = mockFile; at the bottom of your fileMulligatawny
D
6

"Every your events" Like : success - error - sending - removedfile or addedfile and etc.

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

init : function () {
    self.on('Every your events', function (file, response) {
        this.removeFile(file);
    }
}

for remove file from out of this function can do this :

Dropzone.forElement("div#myDrop").removeAllFiles(true);
Disloyal answered 5/12, 2017 at 11:18 Comment(0)
S
6

Try this approach:

 success: function (file, response) {
                    if (this.files.length > 1)
                        this.removeFile(this.files[0]);
                    //Do others tasks...
                }

With this approach the previous item will be removed.

Secretin answered 7/2, 2018 at 3:28 Comment(0)
M
1

Works for me , if the image is already uploaded in the dropzone , it does not allow me to add more .

this.on("addedfile", function(file) {
   /* Valid only in the dropzone . If a repetitive document shows ALERT and the previous item will disappear.(Sorry my English). */
   if (this.files.length) {
     var i, len, pre;
     for (i = 0, len = this.files.length; i < len - 1; i++) {
       if (this.files[i].name == file.name && this.files[i].size == file.size && this.files[i].lastModifiedDate.toString() == file.lastModifiedDate.toString()) {
         alert("Doc: " + file.name + " is already registered.")
         return (pre = file.previewElement) != null ? pre.parentNode.removeChild(file.previewElement) : void 0;
       }
     }
   }
 });
Morea answered 9/3, 2016 at 20:52 Comment(0)
I
0

hi you can just add addRemoveLinks: true, to dropzone function and add success function after dropzon ajax

            success:function(file,response){
              file.serverId = response.id;
    $(".dz-preview:last .dz-remove").attr('onclick','delete_file('+file.serverId+')');
            }

in this code after success upload files comes add into last a tag from dropzone in onclick to call delete_file function and on this function you can receive id and send id to backend, find file in backend and delete files

Isopropyl answered 7/3, 2020 at 5:36 Comment(0)
T
0

You could set maxFiles to 1, or any other number, listen to the maxfilesexceeded event then remove a specific file (the first) from the files array

    $("#dropzone-upload").dropzone({
      init: function() {
        this.on("maxfilesexceeded", function(file){
          this.removeFile(this.files[0])
          alert("Only one file can be uploaded at a time, original file removed!");
        });
      },
      url: "exampleurl",
      maxFiles: 1,
    });
  });
Thessalonians answered 18/10, 2022 at 4:0 Comment(0)
S
0

To remove an existing file in Dropzone, you can use the .removeFile() method on the file object.

Here's an example of how you can use it in your code:

Dropzone.options.dropzonewidget = {
  uploadMultiple: true,
  // other configuration options

  init: function() {
    var dropzone = this;

    $.ajax({
      // your AJAX settings

      success: function(data) {
        var existingFiles = data.existingFiles;

        for (var i = 0; i < existingFiles.length; i++) {
          var file = {
            name: existingFiles[i].name,
            size: existingFiles[i].size
          };

          dropzone.emit("addedfile", file);
          dropzone.emit("complete", file);
          dropzone.createThumbnail(file, "path/to/thumbnail/" + file.name, null, true);
          dropzone.files.push(file);
        }

        for (var i = 0; i < dropzone.files.length; i++) {
          var file = dropzone.files[i];

          if (file.name != "bla.jpg") {
            dropzone.removeFile(file);
          }
        }
      }
    });

    this.on("successmultiple", function() {
      $.ajax({
        // your AJAX settings

        success: function(data) {
          var newFiles = data.newFiles;

          for (var i = 0; i < newFiles.length; i++) {
            dropzone.emit("addedfile", newFiles[i]);
            dropzone.emit("success", newFiles[i], null, newFiles[i].fileObj);
            dropzone.createThumbnail(newFiles[i], newFiles[i].fileObj.path, null, true);
          }

          dropzone.processQueue();
        }
      });
    });

    this.on("removedfile", function(file) {
      $.ajax({
        // your AJAX settings for deleting the file

        success: function() {
         // your success callback
        }
      });
    });
  }
};

In the example above, the existingFiles are added to the Dropzone instance using the .emit("addedfile") method, and then removed from the instance using the .removeFile() method.

The newFiles are added to the Dropzone instance using the .emit("addedfile") method, and the thumbnail is created using the .createThumbnail() method.

September answered 21/3 at 8:48 Comment(0)
S
-1

problem in existing files which are not in dropzone.files array by default and maxFiles option or maxFilesexceeded event will not work as expected. solution: push existing file to files array. Example:

 $("#imagesarea").dropzone({
        url: "https://<yourdomain>/upload",
        maxFiles: 1,
        maxFilesize: 10,
        acceptedFiles: ".jpeg,.jpg,.png",
        timeout: 50000,
        addRemoveLinks: true,
        success: function(file, response){
            //do something on succcess
        },
        error: function(file, response){
            return false;
        },
        maxfilesexceeded: function(file) {
            this.removeAllFiles();
            this.addFile(file);                
        },
        init: function() {
           mockFile = { 
                        name: "320212", 
                        id: 320212, 
                        size: 452810,
                        accepted: true,
                        dataURL: "https://<yourdomain>/file.jpg" 
           };

           //show existing file
           this.displayExistingFile(mockFile, mockFile.dataURL);
           
           //here is important 
           this.files.push(mockFile);
                                
           this.on("removedfile", function (file) {
               //do something when file removed
           });
        }
    });
Sigmoid answered 23/10, 2022 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.