Drag and Drop File Upload using JavaScript and PHP

Are you looking to integrate the drag and drop file upload feature on your website? This feature is much more user-friendly and reduces the clicks of users. It is better than the traditional approach of browsing a file, hitting the submit button.

In this article, we study how to perform drag and drop file upload using JavaScript and PHP.

The final user interface of our file uploader will look something like the image below.

Drag And Drop File Upload

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 feature to upload files is an easy-to-use option for the users. A lot of popular websites like Facebook, WordPress is already using this behavior.

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 the file gets uploaded automatically.

In this tutorial, we are going to give both options to the users. One can upload the file either using drag and drop or through the file input.

I’ll use JavaScript to give an Ajax call which then uploads the file on the server. Using Ajax your page will not reload. It simply sends the file to the server in the background.

Integrate Drag and Drop File Uploader

In order to get started, let’s first write the HTML code. The following HTML code will have a container for file upload. It also includes a CSS and JS file 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 them in the custom.js file. Before that, let’s add some CSS in the style.css file.

#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;
}

Our goal is when a user drops or browses a file, the file should upload to the server automatically. 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.

var fileobj;
function upload_file(e) {
    e.preventDefault();
    fileobj = e.dataTransfer.files[0];
    ajax_file_upload(fileobj);
}
 
function file_explorer() {
    document.getElementById('selectfile').click();
    document.getElementById('selectfile').onchange = function() {
        fileobj = document.getElementById('selectfile').files[0];
        ajax_file_upload(fileobj);
    };
}
 
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) {
                oOutput.innerHTML = "<img src='"+ this.responseText +"' alt='The Image' />";
            } else {
                oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file.";
            }
        }

        xhttp.send(form_data);
    }
}

The JavaScript code is written above automatically detects the options(drag or browse) chosen for uploading a file. Finally, the function ajax_file_upload() takes the file object and passes it to the Ajax call. On receiving a response, it displays the uploaded image in the DOM. If you are not uploading images then comment out that innerHTML part.

Upload file on Server

Finally, in the Ajax file, let’s 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 "false";
    return;
}
 
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 first if the ‘uploads’ directory exists on a server. If not then it creates an ‘uploads’ folder and moves the file inside it. You can adjust this directory path as per your requirement.

I hope you understand how to add drag and drop file upload using PHP and JavaScript. Let me know your thoughts and suggestions in the comment below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

18 thoughts on “Drag and Drop File Upload using JavaScript and PHP

  1. 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)?

  2. 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?

  3. 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

  4. 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

  5. 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.

  6. 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

Leave a Reply

Your email address will not be published. Required fields are marked *