Drag and Drop Multiple File Upload Using JavaScript and PHP

In past, I have written an article Drag and Drop File Upload Using JavaScript and PHP. Some readers asked to write an article on adding a file uploader that allows users to upload multiple files with the drag and drop features.

While working on a web application you may need to upload multiple files with a single uploader on your form. It can help a user to upload single or multiple files in one go. They don’t like to upload multiple files one by one. 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 the Ajax. It means files will be uploaded on the server without reloading a whole page.

Getting Started

As I said, we will not use any external plugin for drag and drop feature. I am going to write all the code from scratch. It is much easier. There is no complex stuff in it. Just follow the steps below and you are done.

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Drag Drop Multiple File Upload</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="custom.js"></script>
</body>
</html>

Here I included style.css and custom.js in which we will add a related code. As we intend to use Ajax, I included a jQuery library.

To give a basic UI for our 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 like below screenshot:

file uploader

Drag and Drop Multiple Files Using JavaScript and PHP

You are set with the basic UI. Now, we can go ahead and write actual code for JavaScript and PHP which upload files on a server. In our HTML I added 2 methods upload_file() and file_explorer() which get call on drop files and select files respectively.

Let’s define these methods and pass the files to the server-side script which uploads files on a server.

custom.js

var fileobj;
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(file_obj) {
    if(file_obj != undefined) {
        var form_data = new FormData();
        for(i=0; i<file_obj.length; i++) {  
            form_data.append('file[]', file_obj[i]);  
        }
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            contentType: false,
            processData: false,
            data: form_data,
            success:function(response) {
                alert(response);
                $('#selectfile').val('');
            }
        });
    }
}

Finally write a server-side code for file upload in the ajax.php file.

ajax.php

<?php
foreach($_FILES['file']['name'] as $key=>$val){
    $file_name = $_FILES['file']['name'][$key];

    // get file extension
    $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    // get filename without extension
    $filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);

    if (!file_exists(getcwd(). '/uploads')) {
        mkdir(getcwd(). '/uploads', 0777);
    }

    $filename_to_store = $filenamewithoutextension. '_' .uniqid(). '.' .$ext;
    move_uploaded_file($_FILES['file']['tmp_name'][$key], getcwd(). '/uploads/'.$filename_to_store);
}
echo "File(s) uploaded successfully";
die;

This code creates a ‘uploads’ directory on your server and stores all files inside this directory. While storing files on a server we take care of keeping the unique name to each uploaded file using the PHP function uniqid().

It’s all about uploading multiple files using the drag-drop feature. I hope you got to know about it. I would like to hear 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.

11 thoughts on “Drag and Drop Multiple File Upload Using JavaScript and PHP

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

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

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

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