How to use Dropzone.js with PHP to Upload Images Only

  JavaScript

Uploading files using drag and drop has been a norm since 2015. Let’s admit, no one likes to click a couple of buttons just to upload a single image, then go back to the very same page just to upload another one. It’s just a LOT of work.

It’s true, back in the days, uploading files is very difficult. Not only that, if you’re a developer, making those file selection inputs are also tedious.

Thankfully, we have found, not only fancier but also an easier way to handle file uploading… and we call it: Drag and Drop.

There are plenty of ways to make a drag and drop upload. One is to create them yourself using vanilla JavaScript, two is by using libraries like Modernizr to detect drag and drop events, and three is by using plugins like Dropzone.js.

DropzoneJS official homepage

In this tutorial, we’re gonna be focusing on how to use the JavaScript plugin that is called Dropzone.js to implement a drag and drop file upload. We’re going to teach you too how to make sure that users can only upload images.

What is DropzoneJS

DropzoneJS is an open-source library that allows users to upload any type of files using drag and drop that even shows a preview of the file that you’re currently uploading.

DropzoneJS made it easier for developers to implement such features just by adding one single line of code. That single line of code will do almost everything for you including the addition of inputs or HTML elements, styles, etc. and the only thing you need to do is to make sure that the file is going somewhere.

Features

DropzoneJS offers the following features:

  • Drag & Drop support
  • Thumbnail images
  • Supports multiple file uploads
  • Progress bar
  • Fully customizable
  • Fully optimized (13KB)
  • Supports almost all browser

Supported Browsers

At this moment, DropzoneJS supports the following browsers:

  • Chrome 7+
  • Firefox 4+
  • IE 10+
  • Opera 12+ (but version 12 for MacOS is currently disabled due to their buggy API)
  • Safari 6+

How to use DropzoneJS

The first thing you need to do to start using DropzoneJS is by downloading the latest version from their project’s GitLab page. At this very moment, the latest version is 5.7.0.

If in case you are not able to download the source files from their GitLab page, you may alternatively go to their CDN page.

By doing so, your script tag should look something like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>

If you wish to use their default drag and drop styling, you can use the following CSS file.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">

Using the sources above, you should have the following HTML code.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>File Upload Example</title>
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">
	</head>
	<body>

		<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>
	</body>
</html>

It’s also important to remember that the project provides two CSS files, the basic.css file which offers a very minimal styling, and a more extensive dropzone.css file. The source files that we’re using above are the minified versions of the DropzoneJS.

Basic Usage

One of the easiest ways to implement dropzone is to apply it to a form element, although according to dropzone’s official documentation, you can use any HTML element such as a <div>.

However, If you’re a starter, we suggest using the form as it requires only a few configurations to set.

You can initialize it just by adding the dropzone class and the action page where you want to send the POST data.

<form id="dropzone-upload-form" method="POST" action="upload.php" class="dropzone"></form>

By using the example above, you should have the following output:

dropzone js drag and drop zone

You may try to upload files and encounter an error where the files were not being uploaded.

dropzone js no action page error

This error only occurs when the file referenced in the action attribute is not present in your project files.

Getting the POST data from Dropzone form

Retrieving data from the dropzone is no different from getting the data from Ajax or XMLHTTPRequest.

They all do the same work true. But, with Dropzone, you don’t need to create an Ajax or request function.

Once you applied the form in your code, all you need to do is make sure that the file is uploaded to your server, and to do that, you’ll need to create the PHP file referenced in the action attribute.

As an example, this will be what’s inside our upload.php file.

<?php

if ( !file_exists( 'images/' ) ) {
    mkdir( 'images/', 0777, true);
}

$imagesFolder = '/images/';
 
if (!empty($_FILES)) {

    $temp = $_FILES['file']['tmp_name'];         
      
    $target = dirname( __FILE__ ) . $imagesFolder;
     
    $finalFile =  $target . $_FILES['file']['name'];
 
    move_uploaded_file( $temp, $finalFile );
     
}
?>  

First off, before we upload the files, let’s check if the folder we want to save our images into is existing. Otherwise, let’s create it using the mkdir() function.

Then, we check if the $_FILES variable is empty. If not, then we assign its file’s temporary name into a new variable $temp and make another set of variables to create the final file that we want to save.

And finally, we use the move_uploaded_file() function to save the files.

With all that, you should be able to save all the files you upload.

dropzone js upload success image

And make sure to check the directory you put in your upload.php file.

dropzone js upload success

Awesome! Now we got our drop and drag file uploader set up.

Modifying Configuration Options

There are multiple ways to configure dropzones.

The first one is to pass an options object instantiating a dropzone.

The second one is to store the configuration somewhere so Dropzone will know how to set up the dropzones when you’re instantiating them.

This can be always done with the Dropzone.options object.

Dropzone.options.myDragAndDropUploader = {
	paramName: "file",
	accept: function(file, done) {
		if (file.name == "weeklyhow.png") {
			done("It is the file.");
		}
		else { 
			done("It is not the file"); 
		}
	}
};
dropzone js error message

Keep in mind that the myDragAndDropUploader is the id of the element of the file uploader. It may be a <div> or anything other than form.

Setting a Maximum File Size

With Dropzones, by default, you can upload files with file size up to 256MB. That is the default maxFileSize value. You could always change the value of this property by adding it to your options object like below.

Dropzone.options.myDragAndDropUploader = {
	paramName: "file",
	maxFilesize: 1,
	accept: function(file, done) {
		if (file.name == "weeklyhow.png") {
			done("It is the file.");
		}
		else { 
			done("It is not the file"); 
		}
	}
};
dropzone js file is too big

Keep in mind that the integer you type in the maxFilesize property only converts into Megabytes. If you need to limit the file size in kilobytes then use decimals.

Restricting Certain File Types

There are two ways to restrict certain file types.

One is to use the upload.php file and make conditions to check if the file is an image.

Two is to use the acceptedFiles parameter to restrict the type of file you want to upload.

Like what we mentioned earlier, we only wanted to upload image files.

So for this, we can accept image files using the following.

Dropzone.options.myDragAndDropUploader = {
	paramName: "file",
	maxFilesize: 10,
	acceptedFiles: 'image/*',
	accept: function(file, done) {
		if (file.name == "weeklyhow.png") {
			done("It is the file.");
		}
		else { 
			done("It is not the file"); 
		}
	}
};

As soon as you click on the file uploader, you should see that it only reads the image files.

dropzone file type limit

And if you try to drag and drop a different file type, you should see the following output.

dropzone wrong file type error

Complete Example

With all the information provided above, you should be able to make the basics of the dropzone.

Using all the source code we provided above, you should also have the following code.

The Index HTML File

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>File Upload Example</title>
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">
	</head>
	<body>
		<form id="myDragAndDropUploader" method="POST" action="test.php" class="dropzone"></form>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>
	</body>
	<script type="text/javascript">
		Dropzone.options.myDragAndDropUploader = {
			paramName: "file",
			maxFilesize: 10,
			acceptedFiles: 'image/*'
		};
	</script>
</html>

The Upload PHP File

<?php

if ( !file_exists( 'images/' ) ) {
    mkdir( 'images/', 0777, true);
}

$imagesFolder = '/images/';
 
if (!empty($_FILES)) {

    $temp = $_FILES['file']['tmp_name'];         
      
    $target = dirname( __FILE__ ) . $imagesFolder;
     
    $finalFile =  $target . changeString( $_FILES['file']['name'] );
 
    move_uploaded_file( $temp, $finalFile );
     
}
?>  

Summary

DropzoneJS is one of the most powerful JavaScript plugins for implementing a drag and drop file upload. In this course, we have learned the basics of all of that. If you are interested in more, we’d love to provide you but in the meantime, we hope that everything we covered here is enough to get you started.

React to this topic

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*