Drag and Drop ajax file upload using DropzoneJS and PHP

Do you want to implement drag and drop AJAX file upload? It has never been easier. With DropzoneJS and PHP, it is super easy.

DropzoneJS or Dropzone.js is a lightweight open source javascript library that provides drag-and-drop file uploads with image previews.

We will begin this post with basic installation of Dropzone. Then, we will do basic file handling on the server. And then finally we will check some important configuration options provided by Dropzone.

How to install DropzoneJS?

Installing dropzone.js is quite straightforward. You just need to download the standalone file and include it in your html page like

<script src="path-to-dropzone/dropzone.js"></script>

Generally we use Dropzone by creating a form element with class dropzone as follows:

<form action="/upload-handling-script"
      class="dropzone"
      id="my-dropzone"></form>

Dropzone automatically attach itself to form elements with the class dropzone. When files are dropped into it, they will be submitted to the specified action attribute. The uploaded files can be handled just as if there would have been a html file input with name ‘file’.

The form element will look like:

Dropzonejs demo

If you want your file uploads to work even without JavaScript, you can include an element with the class fallback. The following code uses fallback class:

<form action="/upload-handling-script" class="dropzone">
  <div class="fallback">
    <input name="file" type="file" multiple />
  </div>
</form>

 

Handling File uploads on the server

You can handle the request on the server as if request is coming from regular HTML form. The following PHP code performs basic file upload:

if (!empty($_FILES)) {
  $tempFile = $_FILES['file']['tmp_name']; 
  $targetFile = 'new_fine_name';
  move_uploaded_file($tempFile, $targetFile);
}

 

So far, we have created basic drag and drop interface using dropzone. Also, we have simple PHP script to handle file upload. Now, we will customize drag and drop by using various configuration options.

More to come… Stay tuned!

Leave a Reply