Drag And Drop File Upload Using JavaScript And PHP

Are you looking to integrate drag and drop file upload for your website? In this article, we study how to add functionality for drag and drop file upload along with traditional choose file option. Our file upload user interface will look like below image.

Drag And Drop File Upload

Why Need Drag And Drop File Upload

Actually, it is a question of creativity. Traditional file uploader also works great. But sometimes, you want to integrate something innovative file uploader like facebook, WordPress etc. It looks better and also improves the user experience for the website.

We are going to integrate AJAX to upload files on the server side. AJAX file upload feature also adds better user experience.

Let’s Integrate Drag And Drop File Uploader

To add this file uploader we first create a container where a user can drag-drop or choose a file. We will write the HTML and CSS code for it as below.

CSS Code

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

HTML Code

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

In the above code we call two functions, first one is upload_file(event) and second one is file_explorer(). Below is the JavaScript code where we declare these two methods. Both methods takes the object of the selected file for upload and pass it to another function ajax_file_upload().

JavaScript Code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  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);
      $.ajax({
        type: 'POST',
        url: 'ajax.php',
        contentType: false,
        processData: false,
        data: form_data,
        success:function(response) {
          alert(response);
          $('#selectfile').val('');
        }
      });
    }
  }
</script>

The function ajax_file_upload() takes the file object and pass it to ajax file. In ajax file, we write the actual code which moves the file on the server. Create a file called ajax.php and add the below code in it.

ajax.php

<?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);
}

move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . time() . '_' . $_FILES['file']['name']);

echo "File uploaded successfully.";
?>

Above PHP code creates a folder called ‘uploads’ and move the uploaded file in it. You can adjust the uploads directory path as per your requirement.

We hope you understand how to add drag and drop file upload by using PHP and JavaScript. If you have any questions or suggestions please leave a comment below.

Related Articles

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

7 thoughts on “Drag And Drop File Upload Using JavaScript And PHP

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

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

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