The example, AJAX multiple files upload using PHP jQuery, will show you how to upload multiple files using PHP, AJAX and jQuery without page refresh. This multiple files upload tutorial example is very useful where you need to upload multiple files in a web application. In this example multiple files are selected using the browse button by holding keyboard’s Ctrl button and files are uploaded to the ‘uploads’ directory. PHP script stores multiple files into the defined location and returns responses as success or failure messages from the PHP script. If you want more file upload link without holding Ctrl button when you select a file then you may read PHP multiple files upload. As a validation step I have added only to check if you have selected at least one file for uploading or not.

You may like to read also AJAX File Upload using PHP, jQuery and AJAX File Upload using Codeigniter, jQuery

Following steps are required in order to complete the example ajax multiple files upload using php jquery. Please go through the following steps.

1.  Include jQuery library.

2.  HTML page with upload field.

3.  jQuery Ajax code.

3.  PHP script to store the file.

Step 1. Include jQuery library into <head/> section of the HTML page. As the example AJAX multiple files upload using PHP jQuery suggests and we know without jQuery or JavaScript technology AJAX will not work, so it is required to include jQuery library. You may also use plain JavaScript to apply AJAX technique but jQuery provides many more functionalities ad easy to use.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Step 2. Put the below upload field inside <body/> tag in HTML page. Notice here how the name attribute is used. We have also used multiple attribute to indicate that we will upload multiple files.

<p id="msg"></p>
<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
<button id="upload">Upload</button>

Step 3. Add below jQuery, AJAX code immediate after the jQuery library inside <head/> section of the HTML page. When Upload button is clicked then we first create a new FormData object to store the file data. We first retrieve the file counts and store each file into FormData object. We then finally send the file data using uploads.php file where server side code is written for uploading to the destination directory.

<script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var form_data = new FormData();
                    var ins = document.getElementById('multiFiles').files.length;
                    for (var x = 0; x < ins; x++) {
                        form_data.append("files[]", document.getElementById('multiFiles').files[x]);
                    }
                    $.ajax({
                        url: 'uploads.php', // point to server-side PHP script 
                        dataType: 'text', // what to expect back from the PHP script
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the PHP script
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the PHP script
                        }
                    });
                });
            });
        </script>

Step 4. Create uploads.php file with below source code. This file is responsible for validation and uploading files to destination directory. The code first checks whether a user has selected at least one file for upload. If user has not selected at least one file then show an error message to the user for selecting at least one file. Then code checks if the selected file already exists in the destination directory then inform with message that the selected file already exists in the destination directory otherwise upload the selected file in the destination directory.

<?php

if (isset($_FILES['files']) && !empty($_FILES['files'])) {
    $no_files = count($_FILES["files"]['name']);
    for ($i = 0; $i < $no_files; $i++) {
        if ($_FILES["files"]["error"][$i] > 0) {
            echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
        } else {
            if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
                echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
            } else {
                move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
                echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
            }
        }
    }
} else {
    echo 'Please choose at least one file';
}
    
/* 
 * End of script
 */

If we combine the steps 1, 2, and 3 then the full source code would be as shown below in a file called files_upload_ajax.php.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>File upload using PHP, jQuery and AJAX</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var form_data = new FormData();
                    var ins = document.getElementById('multiFiles').files.length;
                    for (var x = 0; x < ins; x++) {
                        form_data.append("files[]", document.getElementById('multiFiles').files[x]);
                    }
                    $.ajax({
                        url: 'uploads.php', // point to server-side PHP script 
                        dataType: 'text', // what to expect back from the PHP script
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the PHP script
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the PHP script
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="msg"></p>
        <input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
        <button id="upload">Upload</button>
    </body>
</html>

Now if you run the above file and while selecting multiple files using Ctrl key then you will see below output in the browser.

ajax multiple files upload php jquery

If you try to upload file without selecting any file then you would see error message “Please choose at least one file”.

If the file successfully uploaded then you will see success message “File successfully uploaded : uploads/<some-file-name>“.

If the file you are trying to upload already exists then you will see a message “File already exists : uploads/<some-file-name>“.

Hope you have got an idea on AJAX multiple files upload using PHP jQuery.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

4 thoughts on “AJAX Multiple Files Upload using PHP, jQuery

Leave a Reply

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