84

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.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
pydanny
  • 7,954
  • 6
  • 34
  • 42

13 Answers13

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]);
      }
    });
  }
};
oneirois
  • 1,809
  • 2
  • 10
  • 6
  • 4
    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. – Tom Apr 11 '14 at 15:57
  • where to put this code inside dropzone.js or html codes where form placed –  Jul 14 '15 at 04:29
  • 1
    This is a great answer to a different question (How to overwrite a previously uploaded file). – Rosa Sep 28 '15 at 00:02
  • After trying the other answers, the is the only one that worked exactly how I wanted. Should be accepted answer, imho. – jszobody Jun 07 '16 at 19:38
  • PERFECT!! Works exactly like the way I want – Shilpa Soni Aug 12 '16 at 06:50
  • 1
    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])`? – smoyth Nov 28 '16 at 01:23
  • Thank you Sir! I have been searching long for this. :) – Zolisa Welani Mar 22 '22 at 14:57
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>
Community
  • 1
  • 1
pydanny
  • 7,954
  • 6
  • 34
  • 42
  • shouldn't it be `
    ` ?
    – MK Yung Nov 29 '13 at 07:32
  • 2
    @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.) – Cayce K Sep 17 '14 at 18:00
  • 2
    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? – trs May 25 '15 at 16:05
  • It only worked for me if and only if i put `````` above ```
    ```
    – SagarKapasi099 Jan 07 '22 at 14:16
78

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);
    }
})
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 2
    This didn't work for me -- but the other answer by @oneirois does. – Robert Dodd Dec 04 '14 at 21:35
  • 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). – Pierre de LESPINAY Feb 25 '15 at 17:37
  • This does not work when autoProcessQueue is false. However, it triggers when maxFiles is 0 and autoProcessQueue is false. This must be a bug. – Daantje Feb 15 '16 at 17:10
  • 2
    Worked perfectly fine for me, and agree with this is being most intuitive single file upload process :) – zachu Feb 27 '16 at 18:30
  • +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`. – RNickMcCandless Aug 20 '17 at 22:31
  • @RNickMcCandless good to hear this still is useful so many years later! – Yuji 'Tomita' Tomita Aug 31 '17 at 07:38
  • For me it worked when I added true to removeAllFiles like this: this.removeAllFiles(true); – Augis Apr 03 '20 at 08:56
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);
});
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
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]);
        }
    });
}
xaviert
  • 5,653
  • 6
  • 29
  • 31
5

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

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

vipinlalrv
  • 2,975
  • 1
  • 14
  • 9
  • More of these options can be viewed here: https://www.dropzonejs.com/#configuration-options – Jordan May 22 '19 at 23:12
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);
});
Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
shab
  • 81
  • 1
  • 2
3

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

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

Linga
  • 10,379
  • 10
  • 52
  • 104
Nowell
  • 304
  • 1
  • 5
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

Community
  • 1
  • 1
Timmy Von Heiss
  • 2,160
  • 17
  • 39
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 ;)

SimonDepelchin
  • 2,013
  • 22
  • 18
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.

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);
    }
}
Makah
  • 4,435
  • 3
  • 47
  • 68
-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);
        });
    }
};
Benkerroum Mohamed
  • 1,867
  • 3
  • 13
  • 19