Drag and Drop File Upload using DropzoneJS and PHP

Drag and drop is a very effective feature to make the web application user-friendly. Generally, this feature allows to drag an element and drop it to the different location in the web page. Drag and drop feature can be used for various purposes in the web application. If you want to make file upload functionality more interactive, drag & drop is the best option.

DropzoneJS is an open-source JavaScript library that enables an HTML element dropable. This means the user can drag files from the computer and drop it into this HTML element. DropzoneJS provides an easy way to integrate drag and drop multiple file upload with a preview in the web application. Dropzone is light-weight and does not depend on any other jQuery library.

DropzoneJS does not handle the file upload functionality, it sends the files to the server via AJAX. You need to use PHP to upload files to the server. In this tutorial, we will show you how to integrate drag and drop file upload using DropzoneJS and PHP.

The example code helps you to upload multiple images or files to the server without page refresh using Dropzone and PHP. The following steps will be followed to implement the drag & drop file upload functionality.

  • Droppable element to select multiple files from the computer.
  • Preview of the selected files or images.
  • Upload files to the server using PHP.
  • Insert files information in the database using PHP and MySQL.

Before getting started, take a look at the file structure of drag & drop file upload with PHP.

drag_drop_file_upload_with_php/
├── dbConfig.php
├── index.php
├── upload.php
├── uploads/
├── js/
│   ├── dropzone/
│   │   ├── dropzone.min.js
│   │   └── dropzone.min.css
└── css/
    └── style.css

Create Database Table

To store the information of the uploaded file a table is required in the database. The following SQL creates a files table with some basic fields in the MySQL database.

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database hostname ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

Drag and Drop File Upload (index.html)

The DropzoneJS library will be used to integrate Drag&Drop feature, so, include the Dropzone JS and CSS library first.

<link rel="stylesheet" type="text/css" href="js/dropzone/dropzone.min.css" />
<script type="text/javascript" src="js/dropzone/dropzone.min.js"></script>

Create a form element with class dropzone. Dropzone will attach automatically to this form element and the dropped files data will be posted to the server-side script (specified action URL) for upload.

  • The action attribute of the <form> tag defines the action to perform the server-side upload.
  • The dropzone class is an identifier of the Dropzone library.
<form action="upload.php" class="dropzone"></form>

Upload Files to the Server (upload.php)

Dropzone sends the dropped files to the server-side script (upload.php) to handle the upload process.

  • Retrieve posted file data using the PHP $_FILES method.
  • Upload files to the server using move_uploaded_file() function in PHP.
  • Insert the file info in the database.
<?php 
if(!empty($_FILES)){
    
// Include the database configuration file
    
require 'dbConfig.php';
    
    
// File path configuration
    
$uploadDir "uploads/";
    
$fileName basename($_FILES['file']['name']);
    
$uploadFilePath $uploadDir.$fileName;
    
    
// Upload file to server
    
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){
        
// Insert file information in the database
        
$insert $db->query("INSERT INTO files (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
    }
}
?>

Display Uploaded Files

If you want to display the uploaded files on the web page, you need to fetch the file names from the database and retrieve the respective files from the server.

  • Include the database configuration file to connect and select the database.
  • Fetch the files from the database.
  • Retrieve the files or images from the server (uploads/) and list them on the web page.
  • Since, all types of files (image, pdf, word, video, etc.) can be uploaded, <embed> tag can be used to display files on the web page.
  • Use mime_content_type() function to detect the mime type of the file.
<?php 
// Include the database configuration file
require 'dbConfig.php';

// Get files from the database
$query $db->query("SELECT * FROM files ORDER BY id DESC");

if(
$query->num_rows 0){
    while(
$row $query->fetch_assoc()){
        
$filePath 'uploads/'.$row["file_name"];
        
$fileMime mime_content_type($filePath);
?>
    <embed src="<?php echo $filePath?>" type="<?php echo $fileMime?>" width="350px" height="240px" />
<?php }
}else{ 
?>
    <p>No file(s) found...</p>
<?php ?>

Drag and Drop Reorder Images using jQuery, Ajax, PHP & MySQL

Customize Drag and Drop Upload

Dropzone provides various configuration options to customize the drag and drop files upload. The following example creates dropzone programmatically by initializing Dropzone class and customize the drag & drop upload.

Include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Initialize the Dropzone class and specify the configuration as per your needs.

  • url – File path where the files will be submitted for server-side upload.
  • paramName – The name of the file input field.
  • maxFilesize – Maximum size of the file allowed to upload.
  • maxFiles – Maximum number of files allowed to upload.
  • acceptedFiles – Comma-separated list of allowed mime types.
<script>
//Disabling autoDiscover
Dropzone.autoDiscover = false;

$(function() {
    //Dropzone class
    var myDropzone = new Dropzone(".dropzone", {
        url: "upload.php",
        paramName: "file",
        maxFilesize: 2,
        maxFiles: 10,
        acceptedFiles: "image/*,application/pdf"
    });
});
</script>

Define the HTML element for dropzone and specify the Dropzone class selector.

<div class="dropzone"></div>

Note that: If you use the dropzone class, the default style of DropzoneJS will be assigned. For another ID or class, you need to define custom CSS.

Upload with Button in Dropzone

By default, the upload starts immediately after you drop files on the dropzone. But you can change this behavior by adding a button. The following example shows you how to start file upload on button click in Dropzone.

  • Use the autoProcessQueue option and processQueue method to submit files on button click.
  • Set the autoProcessQueue option to false, that tells Dropzone not to upload the file on the drop.
  • Call processQueue() method to start sending files.
<script>
//Disabling autoDiscover
Dropzone.autoDiscover = false;

$(function() {
    //Dropzone class
    var myDropzone = new Dropzone(".dropzone", {
        url: "upload.php",
        paramName: "file",
        maxFilesize: 2,
        maxFiles: 10,
        acceptedFiles: "image/*,application/pdf",
        autoProcessQueue: false
    });
    
    $('#startUpload').click(function(){           
        myDropzone.processQueue();
    });
});
</script>

Define the HTML element for dropzone and button to trigger the upload process.

<div class="dropzone"></div>
<button id="startUpload">UPLOAD</button>

Drag and Drop File Upload with Dropzone in Codeigniter

Conclusion

This drag and drop file upload script provides a user-friendly way to upload images or files to the server. You can use our example code to upload any types of files (image/pdf/doc/audio/video). Various configuration options are available in DropzoneJS, with these the upload functionality can be easily customized as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

40 Comments

  1. Joseph Mwaka Said...
  2. Antiqu Said...
  3. Seeed Said...
  4. Jack Said...
  5. Ares Hercules Said...
  6. Iqra Khan Said...
  7. Anuragbatra Said...
  8. Veysel Kaya Said...
  9. Chidiebere Said...
  10. Tom Said...
  11. Hiral Said...
  12. Chaoz Said...
  13. Dhaval Said...
  14. Abhishek Said...
  15. Eric Said...
  16. Dhawal Mhatre Said...
  17. Narek Said...
  18. Danil Said...
  19. Narek Said...
    • CodexWorld Said...
  20. Ahmet ERTAN Said...
  21. Dinesh Said...
  22. Kitara Said...
  23. Saobang Said...
  24. Satya Said...
  25. Rajesh Said...
  26. Mack Said...
  27. Phil Said...
  28. RAAJ LOKANATHAN Said...
    • CodexWorld Said...
  29. Waseem Said...
  30. Freddy Said...
  31. Lewis Said...
  32. Lewis Said...
    • CodexWorld Said...
  33. Eddie Lim Said...
  34. Gede Udayana Said...
    • CodexWorld Said...
  35. Sarah Said...

Leave a reply

keyboard_double_arrow_up