Dropzone.js – 1 [upload files]

Dropzone.js is a JavaScript library which provides drag and drops file upload with preview. It works with or without jQuery within the project and also it doesn’t require any other libraries. It doesn’t upload the file to your server. For uploading files, you can use PHP.

You not only upload the file by drag n’ drop you can also use file chooser dialog that’s open when drag n’ drop widget gets clicked. While uploading it shows the progress bar, generates a thumbnail image and shows file size in preview after uploading.

There are some simple steps to build a foolproof uploading system. There is always other ways but you have to an expert to make it work. Those are:

  1. Always load jquery library first if you want to use it.
  2. Then load dropzone js library.
  3. Then you can put your dropzone functionality/customization js script.

So, here is the HTML markup file.

<!DOCTYPE html>
<html>
  <head>
    <title>Dropzone Test</title>
    <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js" integrity="sha256-awEOL+kdrMJU/HUksRrTVHc6GA25FvDEIJ4KaEsFfG4=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" integrity="sha256-e47xOkXs1JXFbjjpoRr1/LhVcqSzRmGmPqsrUQeVs+g=" crossorigin="anonymous" />
  </head>
  <body>
    <form id="demo_upload" action="upload.php" class="dropzone"></form>
  </body>
  <script>
    Dropzone.autoDiscover = false;
    $( document ).ready(function() {
      var myDropzone = new Dropzone("form#demo_upload", {
      });
    });
  </script>
</html>

And here is the PHP file to handle uploads.

<?php
$target_dir = "upload/";

$target_file = $target_dir . basename($_FILES["file"]["name"]);
$msg = ""; 
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
	$msg = "Successfully uploaded"; 
}else{    
	$msg = "Error while uploading"; 
} 
echo $msg;
exit;
?>

This is how the files are arranged:

This is how the demo file upload project looks like:

Leave a Reply

Your email address will not be published. Required fields are marked *