How To Upload Multiple Files In Drag & Drop Box With Preview

Are you looking for a solution to drag and drop multiple files and have a preview at the same time?

Take a look at this post where we created a system that uploads several files to a server using jquery and PHP.

This script will assist you in improving your web application upload mechanism. It is compatible with all browsers.

Step 1: Add “CSS file” to include

<link href="style.css" rel="stylesheet" type="text/css">
<link href="dropzone.css" rel="stylesheet" type="text/css">

Step 2: Add This Code To Javascript & JQuery Library File

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="dropzone.js" type="text/javascript"></script>

Step 3: Add This HTML Code

<div class="container" >
    <div class='content'>
        <form action="upload.php" class="dropzone" id="myAwesomeDropzone"> 
        </form>  
    </div> 
</div>

Step 3: Add This Javascript Code

<script type='text/javascript'>
	Dropzone.autoDiscover = false;
	$(".dropzone").dropzone({
		addRemoveLinks: true,
		removedfile: function(file) {
			var name = file.name;    
			
			$.ajax({
				type: 'POST',
				url: 'upload.php',
				data: {name: name,request: 2},
				sucess: function(data){
					console.log('success: ' + data);
				}
			});
			var _ref;
			return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
		}
	});
</script>

Step 4: Add This PHP Code

$target_dir = "upload/"; // Upload directory

$request = 1;
if(isset($_POST['request'])){
	$request = $_POST['request'];
}

// Upload file
if($request == 1){
	$target_file = $target_dir . basename($_FILES["file"]["name"]);

	$msg = "";
	if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
	    $msg = "Successfully uploaded";
	}else{
	    $msg = "Error while uploading";
	}
	echo $msg;
}

// Remove file
if($request == 2){
	$filename = $target_dir.$_POST['name']; 
	unlink($filename); exit;
}

Step 4: Download Source Code & Upload

Screenshot

The first image shows how the drag-and-drop panel will look after adding the code. And, the second image shows how the files will showcase, once you upload them.

Screenshot 1
drag-drop-file-1

Screenshot 2
drag-drop-file-2