Download uploaded file with DropzoneJs
Asked Answered
M

9

7

I would like to know if it is possible to download files that have been uploaded with Dropzone. For example add to the file that are shown in the dropzone a link or a button to download.

The code for upload and to show the files already uploaded:

index.php

<html>
<head>  
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>

Dropzone.options.myDropzone = {

    init: function() {
        thisDropzone = this;

        $.get('upload.php', function(data) {

            $.each(data, function(key,value){

                var mockFile = { name: value.name, size: value.size };

                thisDropzone.emit("addedfile", mockFile);

                thisDropzone.emit("thumbnail", mockFile, "uploads/"+value.name);

            });

        });


        thisDropzone.on("addedfile", function(file) {

        var removeButton = Dropzone.createElement("<button>Remove</button>");


        var _this = this;

        removeButton.addEventListener("click", function(e) {
          e.preventDefault();
          e.stopPropagation();

          _this.removeFile(file);

        });


        file.previewElement.appendChild(removeButton);
      });


         thisDropzone.on("removedfile", function(file) {
      if (!file.serverId) { return; } 
      $.post("delete-file.php?id=" + file.serverId); 
    });

    }

};
</script> 

</head> 
<body>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>    
</body>
</html>

upload.php

<?php
$ds          = DIRECTORY_SEPARATOR; 

$storeFolder = 'uploads';  

if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];         

    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; 

    $targetFile =  $targetPath. $_FILES['file']['name']; 

    move_uploaded_file($tempFile,$targetFile);

} else {                                                           
    $result  = array();

    $files = scandir($storeFolder);                 
    if ( false!==$files ) {
        foreach ( $files as $file ) {
            if ( '.'!=$file && '..'!=$file) {       
                $obj['name'] = $file;
                $obj['size'] = filesize($storeFolder.$ds.$file);
                $result[] = $obj;
            }
        }
    }

    header('Content-type: text/json');              
    header('Content-type: application/json');
    echo json_encode($result);
}
?>

any help will be much appreciated

Marrakech answered 10/1, 2014 at 17:9 Comment(0)
P
6

Yes I found it possible by altering the dropzone.js file, not ideal for updates but only way I found that worked for me.

Add these 6 lines of code to the addedfile: function around line 539 note Ive marked the code that exists already

// the following line already exists
if (this.options.addRemoveLinks) {

    /* NEW PART */
    file._openLink = Dropzone.createElement("<a class=\"dz-open\" href=\"javascript:undefined;\">Open File</a>");
    file._openLink.addEventListener("click", function(e) {
      e.preventDefault();
      e.stopPropagation();
      window.open("http://www.mywebsite.com/uploadsdirectory/"+file.name);
    });
    /* END OF NEW PART */

    // the following lines already exist
    file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
    file._removeLink.addEventListener("click", function(e) {

Then you'll need to edit the CSS with a class 'dz-open', to style the button.

Poll answered 17/1, 2014 at 13:53 Comment(0)
P
4
myDropzone.on("success", function(file) {
    var a = document.createElement('a');
    a.setAttribute('href',"/uploads/" + file.fullname);
    a.innerHTML = "<br>download";
    file.previewTemplate.appendChild(a);
});
Panjandrum answered 11/10, 2018 at 14:14 Comment(2)
Hi. Thanks for this answer, but can you please add some context? "Code only" answers like this one are hard to use.Linesman
This function is only called, when you upload a file, but not for existing filesCavite
M
1

This can be accomplished using the the example below. You will still need to tweak it to your needs.

I want to display additional information after a file uploaded.

To use the information sent back from the server, use the success event, like this:

Dropzone.options.myDropzone = {
  init: function() {
    this.on("success", function(file, responseText) {
      // Handle the responseText here. For example, 
      // add the text to the preview element:
      file.previewTemplate.appendChild(document.createTextNode(responseText));
    });
  }
};
Monjo answered 10/1, 2014 at 19:7 Comment(0)
S
1

Use this in init function after ajax call. I had the same issue. Solved using this.

$('.dz-details').each(function(index, element) {
    (function(index) {
        $(element).attr('id', "filename_" + index);
        var selectFile = document.querySelector("#filename_" + index);
        selectFile.addEventListener("click", function () {
        window.open("http://localhost:8080/<<contextpath>>/pathtofile/" +  $('#filename_' + index + '> div > span').text());
    });
    }(index));
});
Stinson answered 13/4, 2014 at 6:6 Comment(0)
C
1

you can also add a empty link to your images and when your upload is ready you can fetch the image-src and set it to your link ;)

<a href="#">
  <img src="" data-dz-thumbnail/>
</a>


$("img.data-dz-thumbnail").each(function() {
  $(this).closest("a").attr("href", $(this).attr("src"));
  $(this).closest("a").attr("target", "_blank");
});
Corncrib answered 18/10, 2014 at 22:41 Comment(0)
S
1

My code is something like this.

                success: function(file, rawResponse){
                        file.previewElement.onclick = function() {
                            alert(1);//do download
                        }
                },
Sicanian answered 11/7, 2016 at 15:23 Comment(0)
F
1

code is..

$('.dz-details').each(function(index, element) {
    (function(index) {
    $(element).attr("id", "filename_" + index);
        $("#filename_" + index).on("click", function(){
            window.open("URL/path/folder/" +  $('#filename_' + index + '> div > span').text());
        });
    }(index));
});
Feu answered 13/8, 2020 at 5:53 Comment(0)
S
0

Yes. I found a way by adding a custom preview template (adding a download button there and setting a data-file-id attribute). Then when defining the dropzone on the document ready, I searched for the last generated button element and modified the "data-file-id" attribute to save the file id.

I did the same on the 'success' event of dropzone.

After this I listened to the on click event of the download button and looked for the data-file-id attribute.

var oakDropzone = new Dropzone("#oakDropzone", {
    url: "/trabajo/uploadFile",
    init: function () {

        var trabajoId = $("#trabajoId").val();
        var getArchivosUrl = "/trabajo/getArchivosByTrabajo?trabajoId=" + trabajoId;

        $("#fileLoader").show();

        $.get(getArchivosUrl)
            .done(function (response) {

                for (var i = 0; i < response.data.length; i++) {

                    var file = response.data[i];
                    var fileData = { id: file.Id, name: file.Nombre, size: file.Tamaño, metadata: file.Metadata };
                    fileData.accepted = true;

                    oakDropzone.files.push(fileData);
                    oakDropzone.emit('addedfile', fileData);
                    oakDropzone.emit('thumbnail', fileData, 'data:' + response.data[i].Extension + ';base64,' + response.data[i].Preview);
                    oakDropzone.emit('complete', fileData);

                    $(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', fileData.id);
                }

                $("#fileLoader").hide();

                $('#oakDropzone #template .dz-details .actionButtons .downloadFile').on('click', function (event) {

                    event.preventDefault();

                    var archivoId = $(this).data('file-id');

                    var downloadUrl = "http://localhost:11154/trabajo/downloadFile?fileId=" + archivoId;

                    window.open(downloadUrl, 'blank');
                });

            }).catch(function (response) {

                displayErrorToaster(response);
            });

        this.on("sending", function (file, xhr, formData) {

            formData.append("Id", trabajoId);
            formData.append("File", file);
        });

        this.on("success", function (file, response) {

            file.id = response.data;

            $(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', file.id);

            displaySuccessToaster(response);
        });

        this.on("removedfile", function (file) {

            var deleteUrl = "/trabajo/RemoveFile?fileId=" + file.id;

            $.post(deleteUrl)
                .done(function (response) {
                    displaySuccessToaster(response);
                }).catch(function (response) {
                    displayErrorToaster(response);
                });
        });
    },
    dictRemoveFileConfirmation: 'Realmente desea quitar el archivo seleccionado?',
    dictDefaultMessage: '',
    clickable: "#btnUploadFile",
    previewTemplate: document.querySelector('#previews').innerHTML,
    addRemoveLinks: false
});

This looks like the following image:

Sample Image

Hope this helps you!.

Sharecropper answered 26/10, 2019 at 23:57 Comment(0)
R
0

Mine looks like this, this will add "download" anchor after "remove" and it will directly download the file. ("self" is just dropzone selector)

var a = document.createElement('a');
a.setAttribute('href',existing_file.url);
a.setAttribute('rel',"nofollow");
a.setAttribute('target',"_blank");
a.setAttribute('download',existing_file.name);
                    
a.innerHTML = "<br>download";
self.find(".dz-remove").after(a);
Romp answered 4/8, 2021 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.