Programmatically Add Existing File to Dropzone

The Dropzone FAQ leaves out important settings required to properly preload a dropzone with (an) existing file(s).

My init method for my dropzone:

Dropzone.options.MyDropZoneID = {
    ...
    init: function () {
        var mockFile = { name: fileName, size: fileSize, type: fileMimeType, serverID: 0, accepted: true }; // use actual id server uses to identify the file (e.g. DB unique identifier)
        this.emit("addedfile", mockFile);
        this.createThumbnailFromUrl(mockFile, fileUrl);
        this.emit("success", mockFile);
        this.emit("complete", mockFile);
        this.files.push(mockFile);
        ...

I don't know if the above is a perfect implementation, but it is working correctly with the maxFiles setting. Which is very important if you don't want buggy behavior (like the default message displaying when it shouldn't or extra files getting uploaded). You definitely need to set the accepted property to true and add the file to the files property. The only thing that I think is not required is emitting the success. I haven't played around with that enough though to know for sure.

Note: I used the following NuGet package:

  • Created by: Matias Meno
  • Id: dropzone
  • Version: 4.2.0

If you need to add multiple existing files into Dropzone, declare your existing files as array and then add it into Dropzone programmatically inside a loop like so...

        Dropzone.autoDiscover = false;
        var myDropzone = new Dropzone("#myDropzone", {
            url: "/file/post",
            maxFileSize: 50,
            acceptedFiles: ".pdf",
            addRemoveLinks: true,
            //more dropzone options here
        });

        //Add existing files into dropzone
        var existingFiles = [
            { name: "Filename 1.pdf", size: 12345678 },
            { name: "Filename 2.pdf", size: 12345678 },
            { name: "Filename 3.pdf", size: 12345678 },
            { name: "Filename 4.pdf", size: 12345678 },
            { name: "Filename 5.pdf", size: 12345678 }
        ];

        for (i = 0; i < existingFiles.length; i++) {
            myDropzone.emit("addedfile", existingFiles[i]);
            //myDropzone.emit("thumbnail", existingFiles[i], "/image/url");
            myDropzone.emit("complete", existingFiles[i]);                
        }

Tags:

Dropzone.Js