How to upload a file using Dropzone.js with PHP

Dropzone.js is a lightweight JavaScript library that 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, I am using PHP in this tutorial.

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.

How to upload a file using Dropzone.js with PHP


Contents

  1. Download and Include
  2. HTML
  3. PHP
  4. CSS
  5. Demo
  6. Conclusion

1. Download and Include

  • Download the Dropzone.js library from here.
  • Include dropzone.css and dropzone.js files in your page.
<link href='dropzone.css' type='text/css' rel='stylesheet'>
<script src='dropzone.js' type='text/javascript'></script>

2. HTML

Create a <form > element where add class='dropzone' and set action='upload.php'.

From upload.php file handle file upload when a file is selected.

Completed Code

<!doctype html>
<html>
 <head>
 <link href="style.css" rel="stylesheet" type="text/css">
 <link href="dropzone.css" rel="stylesheet" type="text/css">
 <script src="dropzone.js" type="text/javascript"></script>
 </head>
 <body >
 <div class="container" >
  <div class='content'>
   <form action="upload.php" class="dropzone" id="dropzonewidget">
 
   </form> 
  </div> 
 </div>
 </body>
</html>

3. PHP

Create a new upload folder for storing files and a upload.php file.

Use move_uploaded_file() method to store the file to upload directory.

Completed Code

<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
   $status = 1;
}

4. CSS

Create a style.css file.

.container{
 margin: 0 auto;
 width: 50%;
}

.content{
 padding: 5px;
 margin: 0 auto;
}
.content span{
 width: 250px;
}

.dz-message{
 text-align: center;
 font-size: 28px;
}

5. Demo

View Demo


6. Conclusion

It makes your drag n’ drop uploading process a lot more similar. For implementing it you only need to add the dropzone library and add dropzone class to <form> that’s it.

Use PHP to store the file on the server.

It supported by –

  • Chrome 7+
  • Firefox 4+
  • IE 10+
  • Opera 12+ (Version 12 for MacOS is disabled because their API is buggy)
  • Safari 6+
If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

28 thoughts on “How to upload a file using Dropzone.js with PHP”

  1. sir,
    it is not creating thumbnails for non image files how to create or show custom image at place of greyish box at time of upload

    Reply
    • You can use below script to set custom images for non image files –

      $(“.dropzone”).dropzone({
      init: function() {

      this.on(“success”, function(file) {

      var ext = checkFileExt(file.name);
      var newimage = “”;

      // Check extension
      if(ext != ‘png’ && ext != ‘jpg’ && ext != ‘jpeg’){
      newimage = “upload/logo.png”;
      }

      this.createThumbnailFromUrl(file, newimage);
      });
      }
      });

      // Get file extension
      function checkFileExt(filename){

      filename = filename.toLowerCase();
      return filename.split(‘.’).pop();
      }

      Initialize dropdoze() and check if the file has the specified type of image extensions or not. If it does not have then change thumbnail image source e.g. “upload/logo.png”.

      Here is the demo link.

      Reply
      • Hi,
        I’m a newbie in this ambit, in which part of the code / page, should the script be implemented? And is there any way to implement the functionality of downloading already uploaded files?

        Thanks for your help, regards.

  2. sir,
    how to send a custom error from php file to be previewed if we found that there is error in file that the user uploaded or the user do not have permissions to make upload

    Reply
    • From PHP return your message based on the success or not and in jQuery handle it on dropzone success.

      Dropzone.autoDiscover = false;
      $(“.dropzone”).dropzone({
      init: function() {

      this.on(“success”, function(file,response) {
      alert(response);
      });

      }
      });

      Reply
      • sir where to add above code for that sir my php upload file finds error in file example upload limit exeeded then how my php file process this jquery code with default message sir i need code for my php file so that it could be processed

  3. Thanks for this. How can I get a check to see if the already File Exists, then a prompt to overwrite if it does?

    Reply
    • You can use following code to check and prompt a message on duplicate file case –

      Dropzone.autoDiscover = false;
      $(".dropzone").dropzone({
         init: function() {
                     
           this.on("addedfile", function(file) {
             if (this.files.length) {
               var _i, _len, _ref = this.files.slice();
               for (_i = 0, _len = this.files.length; _i < _len - 1; _i++) {
                                  if (_ref[_i].name === file.name && _ref[_i].size === file.size) {
                                      var r = confirm("Overrite existing file");
                                      if (r == true) {
                                          this.removeFile(_ref[_i]);
                                      }
                                      
                                  }
                              }
                          }
                      });
          }
      });
      Reply
      • I’ve tried many things… but it’s not working.. sir it’ll be very convenient if you post the code for it…

      • I am assuming that you have created separate delete button to remove the image. On the click of the button execute MySQL query to delete it from the database table and unset() method to remove from the folder.

        Example –
        To remove from the database table just update the column with an empty (“”) value or if you have created a separate table for the images storing then delete that image record.

        // Remove image from database table ( Execute this query if their is separate column to store image )
        mysqli_query($con,"update postTable set image='' where id=2");
        OR
        // Remove image from database table ( Execute this query if their is separate table to store images )
        mysqli_query($con,"delete from postTable where id=2");
        
        // Remove from folder ( $imagepath will contain the path of the image to delete )
        unset($imagepath);
        
  4. How can I get the Id of that image and how I can refer a php page when the user clicks the default remove file button in dropzone????

    Reply
    • You can use below code to remove the existing files. Here, I initialized dropzone() and to delete option add addRemoveLinks: true and removefile options.

      From removefile send an AJAX request to delete the file.

      Script
      Dropzone.autoDiscover = false;
      $(“.dropzone”).dropzone({
      init: function() {
      },
      addRemoveLinks: true,
      removedfile: function(file) {
      $.ajax({
      url: ‘delete.php’,
      type: ‘post’,
      data: {name: file.name},
      success: function(data){

      }
      });
      file.previewElement.remove();
      return false;
      }
      });

      delete.php (AJAX file)

      Reply
  5. hello I try to add a dropzone in my website but I have to put it in a form wich is already existing. My probleme is that a can drop file in all the form. how I can do to be able to drop file only on a div

    Reply
    • You need to programmatically define dropzone on <div >.

      Example –
      Update the path of dropzone.css and dropzone.js file.

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <link href="dropzone.css" rel="stylesheet" type="text/css">
      <script src="dropzone.js" type="text/javascript"></script>
      <div class="dropzone">
      <div class="dz-default dz-message">Drag and Drop Here for upload</div>
      </div>
      
      <script type='text/javascript'>
      Dropzone.autoDiscover = false;
      $(".dropzone").dropzone({
      url: "upload.php",
      addRemoveLinks: true,
      success: function (file, response) {
      var imgName = response;
      file.previewElement.classList.add("dz-success");
      },
      error: function (file, response) {
      file.previewElement.classList.add("dz-error");
      }
      });
      
      </script>
      Reply
  6. hello,
    your code is great, thank you.
    i want to upload files but not automatiquely, only if a button is submitted ?
    help please 🙂

    Reply
    • Use following script to upload file on button click –
      Dropzone.autoDiscover = false;
      $(“.dropzone”).dropzone({

      autoProcessQueue: false,
      init: function(){
      var uploadButton = document.getElementById(‘upload’);
      myDropzone = this;

      uploadButton.addEventListener(“click”, function() {
      myDropzone.processQueue();
      });
      }
      });

      Reply
  7. Dear Sir

    How i cant get selected file in database and then i set the file in dropzone (edit menu)

    please help me Thanks a lot sir

    Reply
  8. Please sir my website pops out this issue whenever user wants to upload media to my social community website on moblie devices.. After clicking on the file upload if a user uploads the media directly from the recently used media, it will upload successfully but if a user wants to browse for media in his or her gallery, it displays ‘previous operation unable to complete due to low memory’ issue.
    Please I design the website with the knowledge of WordPress and not programming skills. I will really need you to help me here.
    Thank you.

    Reply

Leave a Comment