Drag and drop is a simple way to allow users to upload their files by dropping them into the container. Nowadays most websites allow uploading using both drag and drop and the file browse e.g. PushBullet, Facebook, SlideShare, etc.
I am using AJAX to save the file to the server which triggers when the file dropped on the target container.
In this tutorial, I show how you can implement a similar type of feature in your project and show a thumbnail when the file is successfully uploaded using jQuery AJAX and PHP.
Contents
1. HTML
I created a <div class="container">
which contains the file element and a <div class="upload-area" id="uploadfile">
container.
I am using this <div>
as file uploading area where the user can drag and drop the file or open File Dialog Box by clicking on it.
Completed Code
<!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="script.js" type="text/javascript"></script> </head> <body > <div class="container" > <input type="file" name="file" id="file"> <!-- Drag and Drop container--> <div class="upload-area" id="uploadfile"> <h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1> </div> </div> </body> </html>
2. CSS
.upload-area{ width: 70%; height: 200px; border: 2px solid lightgray; border-radius: 3px; margin: 0 auto; margin-top: 100px; text-align: center; overflow: auto; } .upload-area:hover{ cursor: pointer; } .upload-area h1{ text-align: center; font-weight: normal; font-family: sans-serif; line-height: 50px; color: darkslategray; } #file{ display: none; } /* Thumbnail */ .thumbnail{ width: 80px; height: 80px; padding: 2px; border: 2px solid lightgray; border-radius: 3px; float: left; } .size{ font-size:12px; }
3. PHP
Create upload
folder and upload.php
file.
Use upload
folder to store files and also added default.png
image which uses as a thumbnail for non-image type files.
Upload file to upload
folder and check file is image or not. If image then assign $location
to $src
.
Initialize $return_arr
Array with file name, size, and location.
Return $return_arr
Array in JSON format.
Completed Code
<?php /* Getting file name */ $filename = $_FILES['file']['name']; /* Getting File size */ $filesize = $_FILES['file']['size']; /* Location */ $location = "upload/".$filename; $return_arr = array(); /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){ $src = "default.png"; // checking file is image or not if(is_array(getimagesize($location))){ $src = $location; } $return_arr = array("name" => $filename,"size" => $filesize, "src"=> $src); } echo json_encode($return_arr);
4. jQuery
The below code stops the page from redirect when the file drop on the page.
// preventing page from redirecting $("html").on("dragover", function(e) { e.preventDefault(); e.stopPropagation(); $("h1").text("Drag here"); }); $("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); });
This removes page default functionality.
Drag & Drop
When the file is dropped on <div class="upload-area">
then storing the file in a variable and creating a FormData Object fd
.
Using append()
method to store the file in FormData variable.
Passing FormData Object variable in uploadData()
function.
From where send AJAX request and using FormData variable as data. When the AJAX successfully callback, passing the response to addThumbnail()
function which creates a new thumbnail and shows its information (name and size).
If the uploaded file is an image then show its image otherwise show the default image.
Click
When the user clicks on the upload area then fire the click event on the file element (id=uploadfile). Onchange event uploading the file and showing the thumbnail same as drag & drop.
Completed Code
$(function() { // preventing page from redirecting $("html").on("dragover", function(e) { e.preventDefault(); e.stopPropagation(); $("h1").text("Drag here"); }); $("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); }); // Drag enter $('.upload-area').on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); $("h1").text("Drop"); }); // Drag over $('.upload-area').on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); $("h1").text("Drop"); }); // Drop $('.upload-area').on('drop', function (e) { e.stopPropagation(); e.preventDefault(); $("h1").text("Upload"); var file = e.originalEvent.dataTransfer.files; var fd = new FormData(); fd.append('file', file[0]); uploadData(fd); }); // Open file selector on div click $("#uploadfile").click(function(){ $("#file").click(); }); // file selected $("#file").change(function(){ var fd = new FormData(); var files = $('#file')[0].files[0]; fd.append('file',files); uploadData(fd); }); }); // Sending AJAX request and upload file function uploadData(formdata){ $.ajax({ url: 'upload.php', type: 'post', data: formdata, contentType: false, processData: false, dataType: 'json', success: function(response){ addThumbnail(response); } }); } // Added thumbnail function addThumbnail(data){ $("#uploadfile h1").remove(); var len = $("#uploadfile div.thumbnail").length; var num = Number(len); num = num + 1; var name = data.name; var size = convertSize(data.size); var src = data.src; // Creating an thumbnail $("#uploadfile").append('<div id="thumbnail_'+num+'" class="thumbnail"></div>'); $("#thumbnail_"+num).append('<img src="'+src+'" width="100%" height="78%">'); $("#thumbnail_"+num).append('<span class="size">'+size+'<span>'); } // Bytes conversion function convertSize(size) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (size == 0) return '0 Byte'; var i = parseInt(Math.floor(Math.log(size) / Math.log(1024))); return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i]; }
5. Output
6. Conclusion
I showed how you implement drag and drop file upload functionality in your project and I didn’t add any type of restriction while uploading the file in PHP which you can add as per your requirement.
If you found this tutorial helpful then don't forget to share.