Upload files by drag and drop using dropzonejs PHP

Last modified: April 07, 2022

Download DropzoneJS from here. As of today, we have a 5.7 version of the dropzone. It is perfect JavaScript library that does not depends on JQuery. In this tutorial, we will look into how to setup a file upload using DropzoneJS and PHP for backend,

Once the download is complete, extract the file. You will need to grab two files from it, dropzone.css and dropzone.js.

Create the folders called uploads, css, and js. Put dropzone.css which you extract from DropzoneJS download folder to css folder and copy dropzone.js to js folders.

folder structure

index.html

Create a index.html file and replace the below file content. We will discuss in detail in a moment.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload</title> <script src="/js/dropzone.js"></script> <link href="/css/dropzone.css" type="text/css" rel="stylesheet" /> </head> <body> <form action="upload.php" class="dropzone"> </form> </body> </html>

In line 8 and line 9, we import Dropzone JavaScript and CSS files. In lines 12-13, we create an HTML form with the class name dropzone. It is important to name form to the dropzone otherwise drag and drop might not work.

file_upload

upload.php

Create a upload.php and copy the content below. We will discuss in detail in a moment.

<?php $separator = DIRECTORY_SEPARATOR; $root_folder = dirname( __FILE__ ); $upload_folder = 'uploads'; $upload_target = $root_folder.$separator.$upload_folder.$separator; if (!empty($_FILES)) { $temp_file = $_FILES['file']['tmp_name']; $target_file = $upload_target. $_FILES['file']['name']; move_uploaded_file($temp_file,$target_file); } ?>

Line 3, DIRECTORY_SEPARATOR in PHP is \ or / to for separator. Line 4 dirname( FILE ), will give the current folder of the application. In line 6, we join them to create an upload target path. Line 8 check if there any upload file, if so it will upload to temporary variable using $_FILES['file']['tmp_name'];. In line 10, it joins the target folder and folder name. Finally, in line 12, it uploads the files to the destination.

file_upload