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 a similar drag and drop technique.

While working on a web application you may require to upload multiple files with a single uploader. Uploading images in the gallery is one of the best examples. In such a case, you never want to upload every single image at a time to your gallery. Having an option to upload images in bulk is always a better solution. It allows a user to upload single or multiple files on their wish. Giving such a file uploader feature adds a better user experience and also speeds up your application.

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

Getting Started

As I said, we will not use any external plugin to achieve our goal. 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.

Let’s create a index.html and add code below in it.

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 to which I will add a code in the next steps.

To give a basic UI for the file uploader let’s add some CSS properties. Of course, you can add your own CSS to give a different look for the file uploader.

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, you should see your file uploader 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 for 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.

Define these methods and pass the files to the server-side script which then stores files on a server.

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() {
        files = document.getElementById('selectfile').files;
        ajax_file_upload(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 server-side code for file upload in 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;

This code creates a ‘uploads’ directory on your server and stores all files inside this directory. You probably want to adjust this directory with yours. While storing files on a server, I am keeping the unique name to each uploaded file using the function uniqid().

It’s all about uploading multiple files using the drag-drop feature. Please share your thoughts and suggestions in the comment section below.

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 *