How to limit the number of dropzone.js files uploaded?
Asked Answered
P

13

85

Depending on the use case, how do I constrain the number of files that dropzone.js will allow?

For example, I might need to only allow 1, 2, or 4 files uploaded.

It's not uploadMultiple. Unfortunately, uploadMultiple only applies to the number of files handled per request.

Parian answered 4/8, 2013 at 23:53 Comment(2)
Use maxFiles. That will helpSinglecross
Actually maxFiles is the answer for this question, there is no need to write more code. thanks.Mammalogy
P
82

Nowell pointed it out that this has been addressed as of August 6th, 2013. A working example using this form might be:

<form class="dropzone" id="my-awesome-dropzone"></form>

You could use this JavaScript:

Dropzone.options.myAwesomeDropzone = {
  maxFiles: 1,
  accept: function(file, done) {
    console.log("uploaded");
    done();
  },
  init: function() {
    this.on("maxfilesexceeded", function(file){
        alert("No more files please!");
    });
  }
};

The dropzone element even gets a special style, so you can do things like:

<style>
  .dz-max-files-reached {background-color: red};
</style>
Parian answered 10/8, 2013 at 9:9 Comment(4)
shouldn't it be <form class="dropzone" id="myAwesomeDropzone"></form> ?Eyre
@MKYung I know this is almost a year after the fact, but the id is pulled by Dropzone and enyo makes the camel case for you. So calling it is much easier. (Can be kinda confusing at first obviously... but it works so I don't complain.)Bugbane
That works fine when adding 1 file, then the next. Although, if you select multiple files on your machine and drag them all to the dropzone form, all of them get added. How to prevent that?Indemnification
It only worked for me if and only if i put <script>Dropzone...</script> above <form>Cleavland
K
173

I achieved this a slightly different way. I just remove the old dropped file any time a new file is added. It acts as overwriting the file which was the user experience I was going for here.

Dropzone.options.myAwesomeDropzone = {
  accept: function(file, done) {
    console.log("uploaded");
    done();
  },
  init: function() {
    this.on("addedfile", function() {
      if (this.files[1]!=null){
        this.removeFile(this.files[0]);
      }
    });
  }
};
Koblas answered 27/9, 2013 at 18:25 Comment(7)
This works really well. The other answers don't. You can also do the same work right within the accept function. this.files exists there as well. This would shorten the code a bit.Alfy
where to put this code inside dropzone.js or html codes where form placedVivyan
This is a great answer to a different question (How to overwrite a previously uploaded file).Mucous
After trying the other answers, the is the only one that worked exactly how I wanted. Should be accepted answer, imho.Frigidarium
PERFECT!! Works exactly like the way I wantKristikristian
For me on current Chrome, files[1] is undefined when there is only one file, so the if condition always returns true. Perhaps just change to if (this.files[1])?Jujube
Thank you Sir! I have been searching long for this. :)Hirsch
P
82

Nowell pointed it out that this has been addressed as of August 6th, 2013. A working example using this form might be:

<form class="dropzone" id="my-awesome-dropzone"></form>

You could use this JavaScript:

Dropzone.options.myAwesomeDropzone = {
  maxFiles: 1,
  accept: function(file, done) {
    console.log("uploaded");
    done();
  },
  init: function() {
    this.on("maxfilesexceeded", function(file){
        alert("No more files please!");
    });
  }
};

The dropzone element even gets a special style, so you can do things like:

<style>
  .dz-max-files-reached {background-color: red};
</style>
Parian answered 10/8, 2013 at 9:9 Comment(4)
shouldn't it be <form class="dropzone" id="myAwesomeDropzone"></form> ?Eyre
@MKYung I know this is almost a year after the fact, but the id is pulled by Dropzone and enyo makes the camel case for you. So calling it is much easier. (Can be kinda confusing at first obviously... but it works so I don't complain.)Bugbane
That works fine when adding 1 file, then the next. Although, if you select multiple files on your machine and drag them all to the dropzone form, all of them get added. How to prevent that?Indemnification
It only worked for me if and only if i put <script>Dropzone...</script> above <form>Cleavland
H
80

I thought that the most intuitive single file upload process was to replace the previous file upon a new entry.

  $(".drop-image").dropzone({
    url: '/cart?upload-engraving=true',
    maxFiles: 1,
    maxfilesexceeded: function(file) {
        this.removeAllFiles();
        this.addFile(file);
    }
})
Headroom answered 21/10, 2013 at 1:50 Comment(7)
This didn't work for me -- but the other answer by @Koblas does.Riffe
Thank you for this hint, that's what I was searching for. Also don't forget to maintain the file server side if applicable (ie: previous file getting deleted).Counterwork
This does not work when autoProcessQueue is false. However, it triggers when maxFiles is 0 and autoProcessQueue is false. This must be a bug.Zenger
Worked perfectly fine for me, and agree with this is being most intuitive single file upload process :)Publicist
+1 This answer is a much better solution for the end-user. Works well on my project using the init: function(){ this.on('maxfilesexceeded', function(file){ this.removeAllFiles(); this.addFile(file); }); } option, even with the added option autoProcessQueue: false.Bronwen
@Bronwen good to hear this still is useful so many years later!Democrat
For me it worked when I added true to removeAllFiles like this: this.removeAllFiles(true);Driggers
A
36

maxFiles: 1 does the job but if you also want to remove the additional files you can use this sample code taken from the Wiki page:

How can I limit the number of files?

You're in luck! Starting with 3.7.0 Dropzone supports the maxFiles option. Simply set it to the desired quantity and you're good to go. If you don't want the rejected files to be viewed, simply register for the maxfilesexceeded event, and remove the file immediately:

myDropzone.on("maxfilesexceeded", function(file)
{
    this.removeFile(file);
});
Await answered 23/9, 2013 at 19:0 Comment(1)
So much underrated answer.Normalcy
S
12

Alternative solution that worked really well for me:

init: function() {
    this.on("addedfile", function(event) {
        while (this.files.length > this.options.maxFiles) {
            this.removeFile(this.files[0]);
        }
    });
}
Specialize answered 24/1, 2018 at 16:25 Comment(0)
W
5

You can limit the number of files uploaded by changing in dropezone.js

Dropzone.prototype.defaultOptions = { maxFiles: 10, }

Waine answered 23/12, 2016 at 8:21 Comment(1)
More of these options can be viewed here: dropzonejs.com/#configuration-optionsMidvictorian
T
5
  1. Set maxFiles Count: maxFiles: 1
  2. In maxfilesexceeded event, clear all files and add a new file:

event: Called for each file that has been rejected because the number of files exceeds the maxFiles limit.

var myDropzone = new Dropzone("div#yourDropzoneID", { url: "/file/post", 
uploadMultiple: false, maxFiles: 1 });

myDropzone.on("maxfilesexceeded", function (file) {
    myDropzone.removeAllFiles();
    myDropzone.addFile(file);
});
Threecornered answered 20/5, 2020 at 1:2 Comment(0)
E
3

it looks like maxFiles is the parameter you are looking for.

https://github.com/enyo/dropzone/blob/master/src/dropzone.coffee#L667

Eads answered 9/8, 2013 at 22:59 Comment(1)
This got added two days after I opened this question. ;-)Parian
P
3

Why do not you just use CSS to disable the click event. When max files is reached, Dropzone will automatically add a class of dz-max-files-reached.

Use css to disable click on dropzone:

.dz-max-files-reached {
          pointer-events: none;
          cursor: default;
}

Credit: this answer

Permanent answered 3/10, 2016 at 20:34 Comment(1)
you won't be able also to remove uploaded by mistake files.Beebeebe
A
0

The problem with the solutions provided is that you can only upload 1 file ever. In my case I needed to upload only 1 file at a time (on click or on drop).

This was my solution..

    Dropzone.options.myDropzone = {
        maxFiles: 2,
        init: function() {
            this.handleFiles = function(files) {
                var file, _i, _len, _results;
                _results = [];
                for (_i = 0, _len = files.length; _i < _len; _i++) {
                    file = files[_i];
                    _results.push(this.addFile(file));
                    // Make sure we don't handle more files than requested
                    if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
                        break;
                    }
                }
                return _results;
            };
            this._addFilesFromItems = function(items) {
                var entry, item, _i, _len, _results;
                _results = [];
                for (_i = 0, _len = items.length; _i < _len; _i++) {
                    item = items[_i];
                    if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) {
                        if (entry.isFile) {
                            _results.push(this.addFile(item.getAsFile()));
                        } else if (entry.isDirectory) {
                            _results.push(this._addFilesFromDirectory(entry, entry.name));
                        } else {
                            _results.push(void 0);
                        }
                    } else if (item.getAsFile != null) {
                        if ((item.kind == null) || item.kind === "file") {
                            _results.push(this.addFile(item.getAsFile()));
                        } else {
                            _results.push(void 0);
                        }
                    } else {
                        _results.push(void 0);
                    }
                    // Make sure we don't handle more files than requested
                    if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
                        break;
                    }
                }
                return _results;
            };
        }
    };

Hope this helps ;)

Abrasion answered 28/4, 2015 at 9:53 Comment(0)
P
0

I'd like to point out. maybe this just happens to me, HOWEVER, when I use this.removeAllFiles() in dropzone, it fires the event COMPLETE and this blows, what I did was check if the fileData was empty or not so I could actually submit the form.

Pliable answered 5/8, 2015 at 18:42 Comment(0)
B
0

You can also add in callbacks - here I'm using Dropzone for Angular

dzCallbacks = {
    'addedfile' : function(file){
        $scope.btSend = false;
        $scope.form.logoFile = file;
    },
    'success' : function(file, xhr){
        $scope.btSend = true;
        console.log(file, xhr);
    },
    'maxfilesexceeded': function(file) {
         $timeout(function() { 
            file._removeLink.click();
        }, 2000);
    }
}
Bobbinet answered 17/8, 2017 at 2:47 Comment(0)
B
-1
Dropzone.options.dpzSingleFile = {
    paramName: "file", // The name that will be used to transfer the file
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    }
};
Bohemian answered 13/7, 2018 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.