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

Demo  Download

Contents

  1. Download and Include
  2. HTML – Create Dropzone container
  3. PHP – Upload file
  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 Dropzone container

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 – Upload file

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.