Drag and Drop Multiple File Upload using JavaScript and PHP

In the past, I have written an article Drag and Drop File Upload using JavaScript and PHP. In that article, I focused on uploading a single file. One of the readers asked how to upload multiple files with the same drag and drop technique.

While working on a web application you may require to upload multiple files at a time. The best example is uploading images in the gallery. In such a case, you don’t want to upload images one by one to your gallery. Having the option to upload images in bulk is a better solution. It allows users to upload single or multiple files. Giving this kind of file uploader adds a better user experience and also speeds up your application.

In this article, I show you how to create this file uploader without using any external plugins. I will upload the files using JavaScript, Ajax, and PHP. It means files will be uploaded on the server without reloading a page.

Getting Started

As I said, I’ll not use any external library to achieve the goal. Instead, I am going to write all the code from scratch. It is simple and easy. There is no complex stuff in it. Just follow the steps below and you are done.

First, create the index.html file and add the code below to it. It’ll add a file container where the user can either drop files or choose files via file explorer.

index.html

<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(s) here</p>
        <p>or</p>
        <p><input type="button" value="Select File(s)" onclick="file_explorer();" /></p>
        <input type="file" id="selectfile" multiple />
    </div>
</div>

<script src="custom.js"></script>

Here I included style.css and custom.js which will be created in the next steps.

To give a basic UI for the file uploader let’s add some CSS properties. I am giving a basic styling to the file uploader. You may wish to add your own CSS to give a different look.

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

After this, the file uploader will display something like the below screenshot:

multiple-file-uploader

Drag and Drop Multiple Files using JavaScript and PHP

We are set with the basic UI. Now, let’s write actual code in JavaScript and PHP which upload files on a server. In the HTML I added 2 methods – upload_file() and file_explorer() that will get called as soon as you drop or select files.

These methods will accept files from the client side and pass them to the server-side script for further processing.

custom.js

function upload_file(e) {
    e.preventDefault();
    ajax_file_upload(e.dataTransfer.files);
}
  
function file_explorer() {
    document.getElementById('selectfile').click();
    document.getElementById('selectfile').onchange = function() {
        ajax_file_upload(document.getElementById('selectfile').files);
    };
}
  
function ajax_file_upload(files_obj) {
    if(files_obj != undefined) {
        var form_data = new FormData();
        for(i=0; i<files_obj.length; i++) {
            form_data.append('file[]', files_obj[i]);
        }
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "ajax.php", true);
        xhttp.onload = function(event) {
            if (xhttp.status == 200) {
                alert(this.responseText);
            } else {
                alert("Error " + xhttp.status + " occurred when trying to upload your file.");
            }
        }
 
        xhttp.send(form_data);
    }
}

Finally, write a PHP code to receive files and uploads them on the server. This code will go inside the ajax.php file.

ajax.php

<?php
if (!file_exists('uploads')) {
    mkdir('uploads', 0777);
}

foreach ($_FILES['file']['name'] as $key=>$val) {
    $filename = uniqid().'_'.$_FILES['file']['name'][$key];

    move_uploaded_file($_FILES['file']['tmp_name'][$key], 'uploads/'.$filename);
}

echo "File(s) uploaded successfully.";
die;

Here, we create the uploads directory on the server and stores all files inside this directory. You probably want to adjust this directory with something else. While storing files on a server, I am keeping the unique name of each uploaded file using the function uniqid(). It saves overriding files with similar names.

It’s all about uploading multiple files using the drag and drop technique. I hope this tutorial should help you to add a file uploader to your project.

Related Articles

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

14 thoughts on “Drag and Drop Multiple File Upload using JavaScript and PHP

  1. Great vanilla JS and PHP code!!! The multifile drag and drop file API is complicated. Its a simple action (drag and drop), but there is so much to it underneath. The non-standard API is difficult to understand because of all the security restrictions. Imagine what bad actors can do with this if it was not very restrictive. Very few useful drag and drop examples on the web that included the PHP script. I spent a month on this, but after this example, I can move on. Thanks Sajid!!!

  2. Figured it out… just this in the .js:

    function upload_file(e) {
    document.write(“Uploading…”);

    then I added a window.location further down:

    success:function(response) {
    alert(response);
    $(‘#selectfile’).val(”);
    window.location = “myurl”
    }

  3. How could I add something to indicate that the files are on their way after they are dropped?

    I am sending up images in many cases and they are quite large, it would help to have a spinner or text that says ‘Files being upload’. I’ve tried a few things but it doesn’t seem like anything runs until the upload is complete.

    How about *something* at the start of the upload_file function? Alert doesn’t show until it is done…

    Thanks

    1. In that case, you need to add some logic. Create the array and append $file_name to it. Return the final array in response and print it using JavaScript.

  4. Great litle drag and drop . Thanks. I would like to drop the files into a different directory which is chnaged by a user variable. chdir() does not seem to have any effect. Help please?

    1. I know this is a bit old to respond, but may help others that have the same question.
      What I did was to add this just before the echo at the bottom:

      rename (‘uploads’, $newlocation);

      Before that I also added code to open a file which had the $newlocation in it which was created by the calling script.

  5. Great tutorial, except IE can not handle the onchange when using file explorer to upload:
    document.getElementById(‘selectfile’).onchange = function() {

    The first select will fail

Leave a Reply

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