Multiple file upload with dropzonejs and PHP

Summary:

There is so many file upload library you will find on the internet. But one of my favorites is dropzone. In this tutorial, you will learn to Upload files using dropzonejs and PHP. You can drag and drop file upload using dropzonejs. Basically dropzone using jquery file upload plugin.

So for this tutorial, you need dropzone.js and dropzone.css which you can download from here

Now, create a file index.php and add following code in it.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/dropzone.css">
        <title>The Code Tutorial - Learn to code!</title>
    </head>
    <body style="margin-top: 100px;">
        <h1 class="brand-title">The Code Tutorial - Learn to code!</h1>
        <div class="container-fluid">
            <div class="dropzone dropzone-previews" id="mydropzone"> <!-- My dropzone stay at this --></div>
        </div>
        <script src="js/jquery.js"></script>
        <script src="js/dropzone.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script>
            jQuery(document).ready(function() {
                Dropzone.autoDiscover = false;
                var myDropZone = jQuery("#mydropzone").dropzone({
                    url: "upload.php",
                    acceptedFiles: "image/jpeg,image/png,image/gif"
                });
            });
        </script>
    </body>
</html>

You can find so many articles on dropzone where dropzone initialized on the form element. But if our form has other elements too it can create a problem so I am using div element to initialize the dropzone.

<div class="dropzone dropzone-previews" id="mydropzone"> <!-- My dropzone stay at this --></div>

The above code is for dropzone. Now let’s understand how this dropzone will be initialized

Dropzone.autoDiscover = false;

The above line is added for the dropzone library to not initialize on its own. If not written above line dropzone will search for class dropzone and initialize the dropzone on its own and it might be possible that your drag and drop functionality will stop.

var myDropZone = jQuery("#mydropzone").dropzone({
	url: "upload.php",
	acceptedFiles: "image/jpeg,image/png,image/gif"
});

The above line in code is for initializing the dropzone. You can see that there are two options

  • url: this parameter will tell dropzone to post file to upload.php.
  • acceptedFiles: This parameter tells dropzone to upload only these files.

By above code your drag and drop functionality is now fully functional. You can now drag and drop your file in dropzone to upload it to the server. Now we need to add code for upload files to server posts by dropzone. So for that please create upload.php file and add following code

<?php
	//added connection.php by require_once for connect and select database 
	// We will discuss this connection later
    require_once('connection.php');
    $upload_dir = "upload/";
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir.$_FILES['file']['name'])) {
        $connection = connectDB();
        $fileName = $upload_dir.$_FILES['file']['name'];
        $sql = "INSERT INTO upload SET upload_path = '".$fileName."' ";
        mysqli_query($connection,$sql);
    }
?>

In the above code, you can see the following code that uploads our file to the desired destination. You can change $upload_dir to upload it to somewhere else in your project

move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir.$_FILES['file']['name'])

Now, Please create connection.php and add the following code in which I have passed certain parameters to select the database.

<?php
function connectDB(){
    $hostname = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'thecodetutorial';
    if ($conn = mysqli_connect($hostname, $username, $password,$database))
        return $conn;
    else
        exit('Error: Could not make a database connection using ' . $username . '@' . $hostname);
}
?>

Now, your dropzone is fully functional and you can upload your files to uploads folder by drag and drop. Also in upload.php the following code which will insert a record on successful file upload.

$connection = connectDB();//Connect to db and select your database
$fileName = $upload_dir.$_FILES['file']['name'];
$sql = "INSERT INTO upload SET upload_path = '".$fileName."' ";
mysqli_query($connection,$sql);

Now, for displaying the uploaded images below dropzone we need to add connection.php file in index.php for connecting and select database. So add following code in index.php at line number 1

<?php
    require_once('connection.php');
?>

Now for showing up the uploaded images below our dropzone element we need to add following code below dropzone element

<div class="row">
<?php
	$connection = connectDB();
	$sql = "SELECT * FROM upload";
	$resource = mysqli_query($connection,$sql);
	while ($result = mysqli_fetch_assoc($resource)) {
		$site_url =  "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
		$imgUrl = $site_url . $result['upload_path'];
		$binUrl = $site_url . 'bin.svg';
		$image_id = $result['id'];
		echo '<div class="md-3 tcrelative" id="image-block-'.$image_id.'">
			<div class="delete" id="'.$image_id.'">
				<img src="'.$binUrl.'" style="color:red;width:20px;height:20px;">
			</div>
			<img src="'.$imgUrl.'" class="img-responsive img-thumbnail" style="width:204px;height:auto;">
		</div>';
	}
?>
</div>

You can see in the above code that I am selecting all the records from the upload table and used a while loop for showing up uploaded images.

Also please download the source code for a better understanding of tutorial and you will also get some more code as well for deleting these uploaded images.

Download Source Code