Tutorial: drag & drop and upload a file using jQuery and PHP

In this tutorial I will explain to you how you can upload a file using jQuery and PHP. You don't need to create a script to upload files via jQuery. You can use jQuery Upload File. jQuery Upload File is an open source plugin which provides multiple file uploads with progress bar.

jQuery Upload File is very simple to use.

You need to create only two files. First file must be a html file. In the html file, add this code:

<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>
<div id="fileuploader">Upload</div>

Next, create a php file, called upload.php with this content:

$output_dir = "uploads/";
$ret = array();

// This is for custom errors;
/* $custom_error= array();
$custom_error['jquery-upload-file-error']="File already exists";
echo json_encode($custom_error);
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
$fileName = $_FILES["myfile"]["name"];
$ret[]= $fileName;
else //Multiple files, file[]
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
$fileName = $_FILES["myfile"]["name"][$i];
$ret[]= $fileName;

echo json_encode($ret);


Users will be able to upload files by using the Upload button or Drag and Drop.

You can download jQuery Upload File from https://github.com/hayageek/jquery-upload-file

Leave a Comment