Are you looking to integrate the drag and drop file upload feature on your website? This feature is much more user-friendly and reduces clicks of the users. It is better than the traditional approach of the browse a file and click the submit button.
In this article, we study how to build drag and drop file uploader using JavaScript and PHP. Here, I am using PHP for server-side operations. The user can pick any preferred language in place of PHP.
The final user interface of our file uploader will look something like the screenshot below.
Why Need Drag and Drop File Upload Feature?
We always want to have a better user experience on the website. Giving the drag and drop file uploader is convenient for users. A lot of popular websites like Facebook and WordPress are already using this technique.
This feature looks better compared to the traditional way of file uploading. It also improves the user experience as the user simply drags the file and it gets uploaded asynchronously.
Our file uploader will have both options. One can upload the file either using drag and drop or through the file input.
I’ll use JavaScript to call the server-side script via Ajax. It simply sends a file to the server asynchronously. All operations will be performed without reloading the whole page.
Integrate Drag and Drop File Uploader
To get started, let’s first write the HTML code. The following HTML will have a container for file upload. It also includes CSS and JS files which I will create in the next steps.
<link rel="stylesheet" href="style.css" />
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>Drop file here</p>
<p>or</p>
<p><input type="button" value="Select File" onclick="file_explorer();" /></p>
<input type="file" id="selectfile" />
</div>
</div>
<div class="img-content"></div>
<script src="custom.js"></script>
In the above HTML, I used 2 events – ondrop
and onclick
. I will define these events in the custom.js
file. Before that, let’s add some CSS to the style.css
.
#drop_file_zone {
background-color: #EEE;
border: #999 5px dashed;
width: 290px;
height: 200px;
padding: 8px;
font-size: 18px;
}
#drag_upload_file {
width:50%;
margin:0 auto;
}
#drag_upload_file p {
text-align: center;
}
#drag_upload_file #selectfile {
display: none;
}
When a user drops or browses a file, we have to upload it to the server. For this, you need to write JavaScript code that takes a file from the client side and sends it to the server.
To handle this scenario, add the following code in the custom.js
file.
function upload_file(e) {
e.preventDefault();
ajax_file_upload(e.dataTransfer.files[0]);
}
function file_explorer() {
document.getElementById('selectfile').click();
}
document.getElementById('selectfile').onchange = function() {
ajax_file_upload(document.getElementById('selectfile').files[0]);
};
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajax.php", true);
xhttp.onload = function(event) {
oOutput = document.querySelector('.img-content');
if (xhttp.status == 200 && this.responseText != "error") {
oOutput.innerHTML = "<img src='"+ this.responseText +"' alt='Image' />";
} else {
oOutput.innerHTML = "Error occurred when trying to upload your file.";
}
}
xhttp.send(form_data);
}
}
This JavaScript code automatically picks the file uploaded via any option. The function ajax_file_upload()
takes the file object and passes it to the server through Ajax. On receiving a response, it displays the uploaded image in the DOM. If you are not displaying images then comment out the innerHTML
part from the code.
Upload file on a Server
Finally, in the server-side script, write the actual code which uploads the file on the server. Create a file called ajax.php
and add the below code to it.
<?php
$arr_file_types = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "error";
die;
}
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = time().'_'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$filename);
echo 'uploads/'.$filename;
die;
This PHP code checks if the uploads
directory exists on a server. If it does not exist, it creates this folder and moves the file inside it. You can adjust this directory path as per your requirement.
Give it a try and you would see your files are uploaded on the server and also displays in the DOM.
I hope you understand how to add drag and drop file upload features using PHP and JavaScript. Let me know your thoughts and suggestions in the comment below.
Related Articles
- Drag and Drop Multiple File Upload using JavaScript and PHP
- Ajax File Upload with PHP and jQuery
- TinyPNG Compress Images using PHP
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
I’ve used your example code in my example of a simple Wiki at http://thepurpletree.uk/v1/HomePage — all my code (everything except Parsedown, Highlight.js and your image uploader) is MIT license. Does your example code have a license? Code is at https://github.com/johnallsup/purple-tree-wiki-v1
The aim of the site is to allow notes to be edited online very quickly. You authenticate somehow, and then press shift-“backtick to edit, content is written in markdown, then (provided you’re authenticated), shift-backtick saves. Your image upload code is used to upload images (with minor adaptations, such as restricting the image upload page to authenticated users).
You can use my code freely in your application. It’s not protected under license.
Another small update from me, when you change HTML code you will be able to uplad also multiple files trought the select file button:
Change this:
——————————————
function file_explorer() {
document.getElementById(‘selectfile’).click();
document.getElementById(‘selectfile’).onchange = function() {
fileobj = document.getElementById(‘selectfile’).files[0];
ajax_file_upload(fileobj);
};
}
——————————————
TO
——————————————
function file_explorer() {
document.getElementById(‘selectfile’).click();
document.getElementById(‘selectfile’).onchange = function() {
const files = document.querySelector(‘[type=file]’).files;
for (i = 0; i < files.length; i++) {
fileobj = document.getElementById('selectfile').files[i];
ajax_file_upload(fileobj);
}
};
}
——————————————
that will allow handling multiple files to be upload via button also
Thank you for this. It works well. My query is that the photo comes in full size to the html page. How do I control the size (I want it half size)?
Add width, height to the img tag.
Sorry to be really thick, but where is the image tag?
Check the below line in custom.js
oOutput.innerHTML = “….”
Thank you for this. I’ve got the upload working. What I’m struggling with now is how to refresh the upload control with the image that was just uploaded. Any suggestions?
I updated the article and included answers to to your question.
Thanx!
Searched for simple and working example… This was the right one!
Nice work!
This is an excellent post. This is really helpful and for my business websites.
i want to hold data till submit any idea??
nice work: thanks!
I’ve got it working locally with with xampp after setting chmod.
I would also like to insert data in a database (via ajax.php) but I can’t get div id=”drop_file_zone” to send more data (e.g. from radio-buttons).
Any ideas?
Thanks
You should append your data to the form_data variable.
Hello everyone,
in my case, I had to remove javascript tags for it works…
nice example.
I have one more example of Drag and Drop File Uploader while working with HTML, Bootstrap.
Thanks
Rk
Hi, I need to pass to “ajax.php” other values (like a form with post).
How can i modifiy JS to obtain it?
Thanks
in HTML
change
———————————
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
———————————
TO
————————
function upload_file(e) {
e.preventDefault();
for (i = 0; i < e.dataTransfer.files.length; i++) {
fileobj = e.dataTransfer.files[i];
ajax_file_upload(fileobj);
}
}
————————————————-
that will allow handling multiple files to be upload
Works like a charm
looks promising, but there’s no pointer to files, and the COPY to clipboard doesn’t work,
and when you select the code, it inludes line numbers which one has to edit out.
Thanks for this example. Really helpful to me. One quick question.
How can we make it upload on the click of a button instead of automatically?
Thanks