Dropzone is easy to set up on the page and upload files using Drag & Drop or file browse.
File preview display after file upload.
It allows you to add or remove file link using addRemoveLinks
option but there is no option for adding a Download link.
In this tutorial, I show how you can add a download link with file thumbnail in the Dropzone container with jQuery and PHP.
Contents
- Download & Include
- HTML – Dropzone container
- PHP – File upload
- jQuery – Initialize Dropzone
- Output
- Conclusion
1. Download & Include
- Download the Dropzone library from here.
- Include dropzone.min.css, jQuery library, and dropzone.min.js in the
<head >
section.
<!-- Dropzone CSS --> <link href="dropzone.min.css" rel="stylesheet" type="text/css"> <!-- jQuery --> <script src="jquery.min.js"></script> <!-- Dropzone JS --> <script src="dropzone.min.js" ></script>
Or you can use CDN –
<!-- Dropzone CSS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" rel="stylesheet" type="text/css"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Dropzone JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
2. HTML – Dropzone container
Create a <div class="dropzone">
to initialize Dropzone.
Completed Code
<!-- Dropzone container --> <div class="dropzone"></div>
3. PHP – File upload
- Create a
ajaxfile.php
andupload
folder to store files. - Assign file upload path to
$target_file
. - Upload a file. If file is uploaded successfully then return the file path (
$target_file
) otherwise, return0
.
Completed Code
<?php $target_dir = "upload/"; // Upload file $target_file = $target_dir . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo $target_file; }else{ echo 0; } die;
4. jQuery – Initialize Dropzone
Set Dropzone autoDiscover
to false
and initialize dropzone on class="dropzone"
.
Set 'ajaxfile.php'
to url
option.
Use success
option to handle dropzone upload response.
To add a download link create an anchor element if the response does not equal to 0
.
Add href
attribute where use response
as value and set target
_blank
.
With innerHTML
add "<br>Download"
text.
Pass anchorEl
to file.previewTemplate.appendChild()
method to add anchor element.
Completed Code
Dropzone.autoDiscover = false; $(".dropzone").dropzone({ url: "ajaxfile.php", success: function (file, response) { if(response != 0){ // Download link var anchorEl = document.createElement('a'); anchorEl.setAttribute('href',response); anchorEl.setAttribute('target','_blank'); anchorEl.innerHTML = "<br>Download"; file.previewTemplate.appendChild(anchorEl); } } });
5. Output
6. Conclusion
Disable Dropzone auto-discovery and use the success
option to create an anchor element for download file. Return file path from AJAX file on successfully upload and use it for anchor href
attribute.