article

Thursday, December 17, 2020

jQuery Ajax Drag and Drop File Upload with PHP and MySQLi

jQuery Ajax Drag and Drop File Upload with PHP and MySQLi

In this tutorial you will learn how to implement drag and drop file upload using jQuery and PHP. 
We will use DropzoneJS jQuery plugin to handle drag and drop file upload functionality.

DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.

It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.

www.dropzonejs.com

Create Database

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL,
  `upload_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

drag_and_drop_upload.php
//drag_and_drop_upload.php
<html>  
 <head>  
  <title>jQuery Ajax Drag and Drop File Upload with PHP and MySQLi</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
 </head>  
 <body> 
<div class="container"> 
	<h2>jQuery Ajax Drag and Drop File Upload with PHP and MySQLi</h2>
	<div class="dropzone">
		<div class="dz-message needsclick">
			<h1>Drop files here or click to upload.</h1>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	$(".dropzone").dropzone({
	  url: 'upload.php',
	  width: 300,
	  height: 300, 
	  progressBarWidth: '100%',
	  maxFileSize: '5MB'
	})
});
</script>	
 </body>  
</html>   
upload.php
//upload.php
<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
if(!empty($_FILES)){     
    $uploadDir = "upload/";
    $fileName = $_FILES['file']['name'];
    $uploadedFile = $uploadDir.$fileName;    
    if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadedFile)) {
        $mysqlInsert = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
		mysqli_query($conn, $mysqlInsert);
    }   
}
?>

Related Post