Add existing image files in Dropzone
Asked Answered
P

8

27

I am using Dropzonejs to add image upload functionality in a Form, as I have various other fields in form so I have set autoProcessQueue to false and Processing it on click on Submit button of Form as shown below.

Dropzone.options.portfolioForm = { 

    url: "/user/portfolio/save",
    previewsContainer: ".dropzone-previews",
    uploadMultiple: true,
    parallelUploads: 8,
    autoProcessQueue: false,
    autoDiscover: false,
    addRemoveLinks: true,
    maxFiles: 8,

    init: function() {

         var myDropzone = this;
         this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {

             e.preventDefault();
             e.stopPropagation();
             myDropzone.processQueue();
         });
     }
 }

This works fine and allows me to process all images sent when form is submitted. However, I also want to be able to see images already uploaded by user when he edits the form again. So I went through following post from Dropzone Wiki. https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server

Which populates dropzone-preview area with existing images but it does not send existing images with form submit this time. I guess this is because theses images are not added in queue but If it's so then how can update on server side, In case an existing image is removed by user?

Also, what would be the better approach, add already added images in queue again or just send information of removed file?

Phalarope answered 27/6, 2014 at 6:54 Comment(0)
R
32

I spent a bit of time trying to add images again, but after battling with it for a while I ended up just sending information about the deleted images back to the server.

When populating dropzone with existing images I attach the image's url to the mockFile object. In the removedfile event I add a hidden input to the form if the file that is being removed is a prepopulated image (determined by testing whether the file that is passed into the event has a url property). I have included the relevant code below:

Dropzone.options.imageDropzone = {
    paramName: 'NewImages',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,
    init: function () {
        var myDropzone = this;

        //Populate any existing thumbnails
        if (thumbnailUrls) {
            for (var i = 0; i < thumbnailUrls.length; i++) {
                var mockFile = { 
                    name: "myimage.jpg", 
                    size: 12345, 
                    type: 'image/jpeg', 
                    status: Dropzone.ADDED, 
                    url: thumbnailUrls[i] 
                };

                // Call the default addedfile event handler
                myDropzone.emit("addedfile", mockFile);

                // And optionally show the thumbnail of the file:
                myDropzone.emit("thumbnail", mockFile, thumbnailUrls[i]);

                myDropzone.files.push(mockFile);
            }
        }

        this.on("removedfile", function (file) {
            // Only files that have been programmatically added should
            // have a url property.
            if (file.url && file.url.trim().length > 0) {
                $("<input type='hidden'>").attr({
                    id: 'DeletedImageUrls',
                    name: 'DeletedImageUrls'
                }).val(file.url).appendTo('#image-form');
            }
        });
    }
});

Server code (asp mvc controller):

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        foreach (var url in viewModel.DeletedImageUrls)
        {
            // Code to remove the image
        }

        foreach (var image in viewModel.NewImages)
        {
            // Code to add the image
        }
    }
}

I hope that helps.

Rubenrubens answered 7/8, 2014 at 9:53 Comment(5)
Thanks Teppic, Yes I had to do the same. :)Phalarope
A litte improvement: Add "accepted: true" to mockFile, so Dropzone recognizes the file as correctly uploaded. This enables for example the limit of uploadable files ('maxFiles')Organography
If i add one file and click submit button, dropzone only fetch newly added image and the existing images will be lost, right ? What can i do in this case ? How can i add existing images in queue for using processQueue() method next ? ThanksBuoyancy
What if you remove multiple files? This solution will send only one urlMicrogroove
with accepted: true you also have to do myDropzone.emit("complete", mockFile); to make it actually set as uploaded, otherwise it will show the upload progress bar which may confuse some!Catch
W
17

To extend on Teppic's answer, I found you needed to emit the complete event to remove the progress bar on the preview.

var file = {
    name: value.name,
    size: value.size,
    status: Dropzone.ADDED,
    accepted: true
};
myDropzone.emit("addedfile", file);                                
myDropzone.emit("thumbnail", file, value.path);
myDropzone.emit("complete", file);
myDropzone.files.push(file);
Wistrup answered 23/8, 2015 at 12:39 Comment(1)
status and accepted is important, if we not put it, the maxFiles will be wrongKarp
S
3

just use myDropzone.addFile(file)

from dropzone source code https://github.com/enyo/dropzone/blob/4e20bd4c508179997b4b172eb66e927f9c0c8564/dist/dropzone.js#L978

Symploce answered 19/10, 2016 at 18:4 Comment(3)
What exactly data should be passed to this function?Oly
I am getting error "Cannot read property 'replace' of undefined" when I try to use addFile(). Is there a special way I need to compose the file object? I'm on Dropzone ver 5.5.Sandhurst
you can pass a javascript File or DropzoneFile, See: github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… and github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… Also, see: developer.mozilla.org/en-US/docs/Web/API/File/…Symploce
F
3

There's an official FAQ for that here

Funderburk answered 29/6, 2019 at 9:55 Comment(1)
I confirm this works as of August 2020 with Dropzone 5.7.2Bohs
M
2

I solved this using the dropzone's built in "displayExistingFile" method.

in your init: function.

  1. Create the mockfile

    let mockFile = { name: file.title, size: file.size, dataURL:};

  2. Call the displayExistingFile function

    this.displayExistingFile(mockFile, , null, 'anonymous')

Instead of 'null' you can place a callback to respond to the thumbnail load event.

The 'anonymous' is for the cross origin property.

Merry answered 2/3, 2020 at 20:11 Comment(1)
I was not able to find a displayExistingFile function in my version (v5.5) of dropzone.jsSandhurst
I
1

Originally I was doing this to programmatically upload a pre-existing file:

myDropzone.emit("addedfile", imageFile);                                
myDropzone.emit("thumbnail", imageFile, imageUrl);
myDropzone.files.push(file);

However, referencing this Dropzone Github Issue I found an easier way to directly upload:

myDropzone.uploadFiles([imageFile])

Unfortunately there are no references to this uploadFiles method in the Dropzone Documentation, so I figured I'd share some knowledge with all you Dropzone users.

Hope this helps someone

Inapprehensible answered 22/4, 2016 at 19:48 Comment(1)
The first portion of your code is mocking the upload process, not really posting anything to the server. and myDropzone.uploadFiles([imageFile]) is posting to server, so they are differentThermal
W
1

If you have the URL of the file, you can add the file with addFile.

fetch("url")
    .then(res => res.blob())
    .then((currentBlob) => {
        const generateFile = new File([currentBlob], "filename.jpg", {
            type: currentBlob.type,
        });
        myDropzone.addFile(generateFile);
    });
Wrennie answered 23/9, 2021 at 2:32 Comment(0)
A
0

On click of upload files just clear the files from dropzone. All Files can be cleared using removeAllFiles() or specific file also you can delete by using removeFile(fileName).

Antecedents answered 23/9, 2014 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.