Add ID to the preview div in Dropzone.js
Asked Answered
W

5

6

I'm trying to add an id attribute to each file uploaded in Dropzone.js, So I can sort it later on.

This is my code:

Dropzone.options.pictureDropzone = {
  paramName: "file",
  addRemoveLinks: true,
  init: function() {
    this.on("success", function(file, response) {
        file.serverId = response.id;
        $(file.previewTemplate).find('.dz-preview').attr('id', "document-" + file.serverId);
    });
  }
};




The line

$(file.previewTemplate).find('.dz-preview').attr('id', "document-" + file.serverId);

Should add the id, but it does nothing. Tried it with prop() too.

If I choose a different element, it does work fine. for example, this works for .dz-details

$(file.previewTemplate).find('.dz-details').attr('id', "document-" + file.serverId);

But I cannot seem to find a way to add it to the dz-preview element.


The HTML structure looks like that:

<div class="dz-preview dz-processing dz-image-preview dz-success">
    <div class="dz-details"> ... </div>
    <div class="dz-progress"> ... </div>
    <div class="dz-success-mark"> ... </div>
</div>



Thank you for the help :)

Whitethroat answered 4/1, 2015 at 11:56 Comment(0)
A
5
this.on("success", function(file, response) {
    file.serverId = response.id;
    $(".dz-preview:last-child").attr('id', "document-" + file.serverId);
});
Amoreta answered 6/1, 2015 at 14:44 Comment(3)
This will fail spectacularly if the user drops multiple files.Revolting
The library doesnt seem to support access to the actual underlaying jQuery objects. Adding attributes to the file object can be achieved with another eventlistener: pastebin.com/p0DCdTrfTrunkfish
So how to make it for multiple files? @SzczepanHołyszewskiBreland
K
29

I know this is old but if anyone is still looking for the answer: -

      this.on("success", function(file, response) {
          file.previewElement.id = response.id;
      });
Kaylenekayley answered 6/1, 2016 at 23:26 Comment(3)
what if i want to put ID on existing images from database?Exasperate
@Exasperate check out this ticket for init function handling existing server files: https://mcmap.net/q/282181/-dropzone-js-v4-display-existing-files-on-server-with-work-limiting-the-number-of-files-and-other-functions then pass in a 4th argument called id to the this.addCustomFile function, add file.previewElement.id = id; somewhere in the function, then in the for loop you add the id from the image that comes from the server via your server code (PHP, etc).Peele
How about multiple files?Breland
W
6

Cast the previewElement into jQuery object and perform any action.

   this.on("success", function(file, response) {
      $(file.previewElement).attr("id", response.id);
  });
Wesleywesleyan answered 27/3, 2018 at 6:22 Comment(2)
file.serverID = response.id I used it this wayAmethist
How to take it from removedfile? @AmethistBreland
A
5
this.on("success", function(file, response) {
    file.serverId = response.id;
    $(".dz-preview:last-child").attr('id', "document-" + file.serverId);
});
Amoreta answered 6/1, 2015 at 14:44 Comment(3)
This will fail spectacularly if the user drops multiple files.Revolting
The library doesnt seem to support access to the actual underlaying jQuery objects. Adding attributes to the file object can be achieved with another eventlistener: pastebin.com/p0DCdTrfTrunkfish
So how to make it for multiple files? @SzczepanHołyszewskiBreland
G
1

I had similar problem but tried it through declaring a variable in javascript ,following is code :

$("#fileUpload${dropdown}").dropzone(
                {

                    url : "uploadAdditionalFile?name="+$("#fileUpload${dropdown} div:first-child").prop('id'),
                    addRemoveLinks : true,
                    maxFiles : 1,
                    init : function() {
                        var imageId = $("#fileUpload${dropdown} div:first-child").prop('id');
                        this.on("maxfilesexceeded",
                            function(file) {
                                    alert("Only one file can be uploaded at a time");
                                    this.removeFile(file);
                                        });
                                this.on("addedfile",
                                        function(file) {
                                            switch (file.type) {
                                            case 'application/pdf':
                                                this.emit("thumbnail",file,"/sbms/static/img/pdf.png");
                                                break;
                                            case 'application/msword':
                                                this.emit("thumbnail",file,"/sbms/static/img/word.png");
                                                break;
                                            }
                                        }
                                );
                                 this.on('removedfile', function(file){
                                     $.ajax({
                                            type : "GET",
                                            url : "removeAdditionalMediaPreviewForm?id="+imageId,
                                            dataType : "json",
                                            async : false,
                                            success : function(response) {
                                                if (response.status == 'SUCCESS') {
                                                    alert("File removed successfully.")
                                                }else {
                                                    alert("File not removed successfully.")
                                                }
                                            }
                                        });
                                }); 

                    },

                    success : function(file,response) {
                        var imgName = response;
                        file.previewElement.classList.add("dz-success");
                        console.log("Successfully uploaded :"+ imgName);
                    },
                    error : function(file,response, xhr) {
                        alert("Unable to upload file. Please check if it is a valid doc or pdf file.");
                        this.removeFile(file);
                    }
                });

imageId is a variable which stores the id and is used later on while file remove.

Geometrize answered 15/7, 2016 at 6:18 Comment(0)
H
0

This will fail spectacularly if the user drops multiple files.(Szczepan Hołyszewski Dec 17 '15 at 18:45);

BryanFoong answer won't fail if you set the option uploadMultiple: false. Which is set so by default. In this case Dropzone sends separate request to the server for each file. Therefore "success" event triggers for each individual file.

In case the uploadMultiple: true. Dropzone will send single request to server for all files. And "success" event will trigger once. And following code will handle that.

    YourDropzoneInstance.on("success", function(file, response) {
        response.files.forEach(function(file) {
            file.previewTemplate.id = file.id;
        })
    })

Again you need to return from server array of files. In PHP it will look like

    function yourFileUploadHandler() {
        ...
        // your server file upload implementation        

        $response = [
            "files" => [
                ["id" = 1, ...],
                ["id" = 2, ...],
                ...
             ],
        ];
    
        return json_decode($response);
    }
Heptamerous answered 18/4, 2021 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.