Drag and drop is a very effective feature to make the web application user-friendly. Generally, this feature allows you to drag and drop an element to a different location on the web page. The 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 them into this HTML element. DropzoneJS provides an easy way to integrate drag and drop multiple file uploads 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.
Before getting started, take a look at the file structure of drag & drop file upload with PHP.
drag_drop_file_upload_with_php/ ├── index.html ├── dbConfig.php ├── upload.php ├── uploads/ └── js/ ├── dropzone.min.js └── dropzone.min.css
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;
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);
}
The DropzoneJS library will be used to integrate Drag&Drop feature, so, include the Dropzone JS and CSS library first.
<script src="js/dropzone/dropzone.min.js"></script>
<link href="js/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
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.
<form action="upload.php" class="dropzone"></form>
Dropzone sends the dropped files to the server-side script (upload.php
) to handle the upload process.
<?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())");
}
}
?>
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.
<?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
Dropzone provides various configuration options to customize the drag-and-drop file upload. The following example creates a dropzone object programmatically by initializing the Dropzone class, and customize the drag & drop upload.
Include the jQuery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.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 has been added as a global variable.
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.
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.
autoProcessQueue
option and processQueue method to submit files on button click.autoProcessQueue
option to false, that tells Dropzone not to upload the file on the drop.processQueue()
method to start sending files.<script>
//Disabling autoDiscover
Dropzone.autoDiscover = false;
$(function() {
// Dropzone has been added as a global variable.
var myDropzone = new Dropzone(".dropzone", {
url: "upload.php",
paramName: "file",
maxFilesize: 2,
maxFiles: 10,
parallelUploads: 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
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 file types (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
THanks for the redirection solution after successfull upload
how to do server side validation?
can we upload image to folder image , files to folder fils?
Hey… amazing tutorial, can you add a new addition to it for chunking uploads as Dropzone.js now supports it!
I cannot upload files which are greater than 2MB even after modifying php.ini file
Follow these instructions to increase the file upload size in PHP – https://www.codexworld.com/how-to/increase-file-upload-size-php/
how we allow only single file upload and when we click on submit then insert into database.
sir,
it is not creating thumbnails for non image files how to create or show custom image at place of greyish box for non image files at time of upload
Hello..
Thank you very much for this example. Very practical and useful.
I want to get the name and some information of the user who sent the file with it. how can I do it..
Thank you…
Thanks for this great tutorial.. but i would like to know if i can remain the image path before the image gets to the folder and uploaded.
Nice, its working but the only sad thing is when someone have other input fields like “name” ect.. The entire form is dropzone 🙁
Hii,
Thanx for shaing. But I want to create thumbnail and compress the image but no idea, please help me…!
Hi… tq for the tutorial and code…
however..my dropzone does not working when i tried to load it on my webpage using xml request…
do you / anyone know where the problem lies..?
how to restrict user to upload maximun files.???
How to change it for upload a single file, if upload second file replace previous file. I need to show only latest file box.
great code, thanks a lot!
I have adapted a couple of things to my needs but I can’t find how to restrict certain file types.
I tried changing the line “acceptedFiles: null,” but somehow all my attempt failed.
how can I do this?
thanks
Hello,
Thanks for this easy tutorial for uploading multiple files, i have couple of query
– is there any possibility of validation of extension such as i want to upload only images
– is there any way to print the count of uploaded image.???
Hello. How can I add a button ” upload” in order while pressing it pictures which have been uploaded in drop zone would be added in the mysql base and upload folder?
Hi, your tutotial is realy great, but is it possible to upload files with folders with saved file tree. I mean upload foled “mydir” like this:
uploads/mydir/1.png
uploads/mydir/onmoredir/2.png
uploads/mydir/onmoredir/3.png
Hi i have some problem)) It’s really nice post but when i try to upload files with large size like 6.3 or 6.7 MB it’s not work)) 0 result in db and in upload folder(( can you help me? Thank you in advance))
You need to increase the value of
upload_max_filesize
andpost_max_size
inphp.ini
file:hi,
this is fantastic.
i have a question;
Is it possible to upload pictures made in the same form deletion process before the records in the database
thanks
Hi CodexWorld,
Thanks for great code but I need really code how to delete file from server + mysql database.
I will be really helpful.
Thank you in advance.
Hi, love your tutorial. Finally something easy and straight to the point that we can understand. I have another question that I have been googling for a while, is it possible to add extra file information input from the user? Like Title, Description for each file? Thank you a lot!
nice post. thank u . it really helpful for me but how can i use it with submit button and save name of all picture to array then save them to database. can u help me?
Nice post….:-)
hi….superb ,its really nice.. can u tell me how to upload drag and drop images with submit button..can u tell me pls
How would I send a description of the image and store it in the database
this code is really cool. I finally update both the database and the json file at upload, so get best of both world. Not sure yet how to display the caption…did not see the option yet..
Why i tried but mine is not working? Are there any changes needed for it? After i upload the image, my phpmyadmin showing zero results inserted
@Raaj You need to change the
$dbHost
,$dbUsername
,$dbPassword
, and$dbName
variables value with your MySQL database details inupload.php
file.hey how can we imply validation for only jpg, jpeg, png, gif images ? Please help. And yeah thanks for this nice and short method.
how to prevent dropzone directly images store in database before click submit button ? can you give me example code pragammatically js
how can make validations in dropzone such as witdh and height also ?
Thanks
Perfect that worked, thanks!
In order to implement the redirect on success where does the following code need to go? Is it in the dropzone.js file, in the index or the upload file?
@Lewis
Place this code in index.html file.
Hello! Great tutorial here, super easy to understand! But i have a few questions.
1) I realized that I am unable to upload png files. How can i let png to be uploaded?
2) How do i select the pictures from sql and view it in a gallery style?
sorry for any inconvenience caused. I just started learning web designing 2months ago.
any help and advice will be greatly appreciated! 🙂 Thanks in advance!
Hi,
It’s nice and simple script. Thank you a lot. However i need additional code, how to, if we need to redirect to specific link after uploads finished, like redirect to http://mydomain.com?file=
Thank you in advance.
Gede Udayana
Thanks Gede.
For using Dropzone events, we need to create Dropzone programmatically. This code uses jQuery, so you need to include the jQuery library first. Now Dropzone codes with jQuery library would like the below. You need to modify the
window.location.href
value with your desired redirect URL.Thanks a lot. I have implemented the drag and drop file upload very easily with this tutorial.