Drag and Drop ajax file upload using DropzoneJS and PHP

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
  1. <script src="path-to-dropzone/dropzone.js"></script>
Generally we use Dropzone by creating a form element with class dropzone as follows:
  1. <form action="/upload-handling-script"
  2. class="dropzone"
  3. 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:
  1. <form action="/upload-handling-script" class="dropzone">
  2. <div class="fallback">
  3. <input name="file" type="file" multiple />
  4. </div>
  5. </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:
  1. if (!empty($_FILES)) {
  2. $tempFile = $_FILES['file']['tmp_name'];
  3. $targetFile = 'new_fine_name';
  4. move_uploaded_file($tempFile, $targetFile);
  5. }

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:
  1. Dropzone.options.dropzoneElement = {
  2. 'option' : 'value'
  3. }
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.
  1. Dropzone.options.dropzoneElement = {
  2. maxFiles: 1,
  3. maxFilesize: 500, // File size in Mb
  4. acceptedFiles: 'application/pdf'
  5. }
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.
  1. Dropzone.options.dropzoneElement = {
  2. maxFilesize: 500,
  3. autoProcessQueue: false,
  4. init: function() {
  5. var submitButton = document.querySelector("#btnUpload")
  6. myDropzone = this;
  7. submitButton.addEventListener("click", function() {
  8. /* Check if file is selected for upload */
  9. if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
  10. alert('No file selected for upload');
  11. return false;
  12. }
  13. else {
  14. /* Remove event listener and start processing */
  15. myDropzone.removeEventListeners();
  16. myDropzone.processQueue();
  17. }
  18. });
  19. /* On Success, do whatever you want */
  20. this.on("success", function(file, responseText) {
  21. alert('Success');
  22. });
  23. }
  24. };

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:
  1. Dropzone.options.dropzoneElement = {
  2. init: function() {
  3. this.on("sending", function(file, xhr, formData) {
  4. formData.append("status", 'new');
  5. formData.append("user_id", 1);
  6. });
  7. this.on("success", function(file, responseText) {
  8. alert('Success');
  9. });
  10. }
  11. };

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.
I hope this post is very useful. Please feel free to add your question by droping a comment below.

Comments