dropzone upload only one file

2020-05-19 04:14发布

问题:

I am using dropzone.js for my drag-drop file upload solution. I want to upload only one file,if i upload second file the first one should be remove and second one should be uploaded. any idea how to do it..

here is my html

<form class="dropzone dz-clickable" action="upload.php" enctype='multipart/form-data'>
  <i class="fa fa-cloud-upload element"></i>
  <div style="color:gray;">Drag and drop or click to upload image</div>
  <input type="hidden" name="filenameEmail" class="filenameEmail" value="">
  <input type="hidden" name="side" value="front">
</form>

i changed dropzone.js

maxFiles: 1

it allow to upload only one file but i cant remove the previously uploaded file.please help me out.thanks in advance

回答1:

maxFiles: 1 is used to tell dropzone that there should be only one file. When there is more than 1 file the function maxfilesexceeded will be called, with the exceeding file as the first parameter.

here is a simple function to delete preview of first file and add the new one :)

maxFiles:1,
init: function() {
      this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
      });
}   


回答2:

I used event maxfilesexceeded with method addFile and rans into infinite loop of event call. It should be the problem of using addFile because I didn't see it mentioned in both official site or GitHub wiki. Finally I solved with addedfile event. The Dropzone.js is the latest version when I write (4.3.0).

init: function() {
  this.on('addedfile', function(file) {
    if (this.files.length > 1) {
      this.removeFile(this.files[0]);
    }
  });
}


回答3:

Limiting maxFiles to 1 still allow selecting multiple files in upload dialog. To disallow selecting multiple images in configuration specify following init function:

maxFiles:1,
init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
}  


回答4:

 Dropzone.prototype.defaultOptions.init = function () {

                 this.hiddenFileInput.removeAttribute('multiple');
                 this.on("maxfilesexceeded", function (file) {
                     this.removeAllFiles();
                     this.addFile(file);
                 });
             };

this is wokrk for me.



回答5:

None of these solutions worked for me.

The maxfilesexceeded event is called too late i.e. after an attempt to add the file.

Other solutions using this.removeFile(this.files[0]); resulted in a "Uncaught TypeError: Cannot read property 'removeChild' of null". or an infinite loop.

Solved by -

maxFiles: 2,
init: function () {

    this.on("addedfile", function (file) {
        if (this.files.length > 1) {
            this.files = this.files.slice(1, 2);                        
        }
    });

}

Works when using dz-clickable (file chooser btn) and drag and drop.