PHP drag and drop file upload tutorial using dropzone.js


dropzone.js is a Open Source under MIT Licience library that lets you upload files (images, pdfs, text files, docs e.t.c) to the server via simple drag-and-drop option.

This tutorial provides an example with PHP :

Steps :

Download the js dropzone-amd-module.js and css - dropzone.css from github : https://github.com/enyo/dropzone.

Create a HTML page that with file upload form :

Example: drag-drop-example.html
<html>

<head>
<title>Drag drop Images, PDF, Docs and other files Example : PHP + Dropzone.js</title>

<script src="js/dropzone.js"></script>

<style type="text/css">
/*
 * The MIT License
 * Copyright (c) 2012 Matias Meno <m@tias.me>
 */
.dropzone,.dropzone * {
	box-sizing: border-box;
}

.dropzone {
	position: relative;
}

.dropzone .dz-preview {
	position: relative;
	display: inline-block;
	width: 120px;
	margin: 0.5em;
}

.dropzone .dz-preview .dz-progress {
	display: block;
	height: 15px;
	border: 1px solid #aaa;
}

.dropzone .dz-preview .dz-progress .dz-upload {
	display: block;
	height: 100%;
	width: 0;
	background: green;
}

.dropzone .dz-preview .dz-error-message {
	color: red;
	display: none;
}

.dropzone .dz-preview.dz-error .dz-error-message,.dropzone .dz-preview.dz-error .dz-error-mark
	{
	display: block;
}

.dropzone .dz-preview.dz-success .dz-success-mark {
	display: block;
}

.dropzone .dz-preview .dz-error-mark,.dropzone .dz-preview .dz-success-mark
	{
	position: absolute;
	display: none;
	left: 30px;
	top: 30px;
	width: 54px;
	height: 58px;
	left: 50%;
	margin-left: -27px;
}


/* Custom decoration code */ 
.decoration {
	border: 1px dashed #999;
	background: #f2f2f2;
	padding: 20px;
}
</style>
</head>

<body>
<div>
<form action="upload-files.php" class="dropzone decoration"
id="my-awesome-dropzone"></form>


<script type="text/javascript">

Dropzone.options.myAwesomeDropzone = {
		  maxFilesize: 20, // Size in MB
		  addRemoveLinks: true,
		    removedfile: function(file) { 
		      var fileRef;
		      return (fileRef = file.previewElement) != null ? 
				      fileRef.parentNode.removeChild(file.previewElement) : void 0;
		    },

	success: function(file, response) {
		    	  alert(response);
		    	},

	error: function(file, response) {
			    	  alert(response);
			    }
	    	
};



</script></div>
</body>

</html>
Create a PHP page to upload files to the server :
<?php
//PHP code to upload file to server directory
if (!empty($_FILES)) {
	 
	$temporaryFile = $_FILES['file']['tmp_name'];     
	$targetFile =  "uploaded-file-dir-location". $_FILES['file']['name'];
	if(!move_uploaded_file($temporaryFile,$targetFile))  {
		echo "Error occurred while uploading the file to server!";		
	}
}
?>


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap