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 DropzoneJS.

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.

If you have HTML elements with the dropzone class, you can configure dropzones with the Dropzone.options object as follows:

Dropzone.options.dropzoneElement = {
  'option' : 'value'
}

where ‘dropzoneElement‘ is the camelized version of the HTML element’s ID.

Limiting number of files, filesize and file type in dropzone

You can limit the number of files using the option ‘maxFiles‘. Similarly, you can limit the maximum filesize allowed and file type by using the options ‘maxFilesize‘ and ‘acceptedFiles‘ respectively.

Dropzone.options.dropzoneElement = {
  maxFiles: 1,
  maxFilesize: 500, // File size in Mb
  acceptedFiles: 'application/pdf'
}

Preventing auto upload (auto process)

By setting autoProcessQueue to false, you can prevent files to be uploaded automatically. This option is extremely helpful if you are using external element like button to start file processing or sending all files at once. The following snippet uses a button with id ‘btnUpload‘ to send the file.

Dropzone.options.dropzoneElement = {
  maxFilesize: 500,
  autoProcessQueue: false,
  init: function() {
                    
    var submitButton = document.querySelector("#btnUpload")
    myDropzone = this;
    
    submitButton.addEventListener("click", function() {
      
      /* Check if file is selected for upload */
      if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {			
        alert('No file selected for upload');	
        return false;
      }
      else {
        /* Remove event listener and start processing */ 
        myDropzone.removeEventListeners();
        myDropzone.processQueue(); 
        
      }

    });
    
    
    /* On Success, do whatever you want */
    this.on("success", function(file, responseText) {			
      alert('Success');
    });
  }   
};

Sending additional data with dropzone

Now lets find out how to send additional data or parameter with dropzone.

Just like we did in above example, we can use dropzone another event to accomplish this task.

The event ‘sending‘ is called just before each file is sent. Here’s the code:

Dropzone.options.dropzoneElement = {

  init: function() {
                    
    this.on("sending", function(file, xhr, formData) {
      formData.append("status", 'new');
      formData.append("user_id", 1);

    });
    
    
    this.on("success", function(file, responseText) {			
      alert('Success');
    });
  }   
};

In Conclusion

Dropzone.js is very useful tool. It is very easy to use as well as flexible. Check Dropzone documenation for more configuration options and events.

You may like: Multiple files using HTML and PHP.

I hope this post is very useful. Please feel free to add your question by droping a comment below.

 

5 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.