Home » Php » javascript – Download uploaded file with DropzoneJs

javascript – Download uploaded file with DropzoneJs

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

myDropzone.on("success", function(file) {
    var a = document.createElement('a');
    a.setAttribute('href',"/uploads/" + file.fullname);
    a.innerHTML = "<br>download";
    file.previewTemplate.appendChild(a);
});

Answer:

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));
    });
  }
};

Answer:

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));
});

Answer:

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");
});

Answer:

My code is something like this.

                success: function(file, rawResponse){
                        file.previewElement.onclick = function() {
                            alert(1);//do download
                        }
                },

Answer:

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!.