Upload Multiple Files with JavaScript using PHP

Mostly the server-side scripting language such as PHP is used to upload file to the server. With this method, an HTML form is submitted to upload the selected file to the server. To provide a better user interface, we can use client-side technology such as jQuery Ajax to upload files without page refresh. Moreover, you can use simple JavaScript to upload files to the server.

The JavaScript FormData interface provides an easy way to construct key/value pairs with form fields and send them to the server side using the XMLHttpRequest method. This technique can be used to upload files to the server with JavaScript. In this tutorial, we will show you how to upload multiple files using JavaScript.

In this example, we will use the FormData object to post file data to server-side script with JavaScript and upload multiple files to the server using PHP.

  • Define HTML input element to select files.
  • Restrict file types and size before uploading using JavaScript.
  • Construct file data with the FormData interface.
  • Send multiple files to the server-side using the fetch() method.
  • Upload multiple files to the server using PHP.

Multiple Files Upload with JavaScript (index.html)

HTML Code:
Create <input> elements with type="file" to let the user select files.

  • Add multiple attribute to allow the user to select more than one file.
  • Specify the file types and size validation handler function (fileValidation) in onchange event.
  • Define a <button> element to initiate the file upload request.
  • Specify the file upload handler method (UploadFiles) in the onclick event.
<div class="wrapper">
    <!-- Status message -->
    <div id="status-msg"></div>

    <!-- File upload form -->
    <div class="form-group">
        <label>Select Files:</label>
        <input type="file" class="form-control" id="file_input" onchange="return fileValidation()" multiple>
    </div>

    <button id="uploadBtn" class="btn btn-primary" onclick="UploadFiles()">Upload</button>
</div>

JavaScript Code:
1. The fileValidation() function handles the file size and type validation process.

  • Validate file types and size before uploading multiple files with JavaScript.
  • Specify the file types in the allowedExtensions variable that are allowed to be uploaded. It will check the type of the selected files and restrict if any file is selected other than the allowed file types.
  • Specify the file size in the allowedTotalSize variable that is allowed to be uploaded. It will validate the combined size of all select files and make sure not exceed the allowed size.

2. The UploadFiles() function handles the multiple file upload with JavaScript.

  • Define formData object and multiple files data using formData.append() method.
  • Send file data to the server-side script (upload_init.php) using the fetch() method.
  • Display status message based on the response received from the server side.
<script>
//File type and size validation handler function
function fileValidation(){
    let allowedExtensions = /(\.jpg|\.jpeg|\.png|\.pdf)$/i;
    let allowedTotalSize = 20; //in MB

    const fileInput = document.getElementById('file_input');
    let fileInput_length = fileInput.files.length;
    
    let fileSize = 0;
    if (fileInput_length > 0) {
        for (var i = 0; i < fileInput_length; i++) {
            fileSize = fileSize+fileInput.files[i].size;

            if(!allowedExtensions.exec(fileInput.files[i].name)){
                alert('Please upload file having extensions .jpeg/.jpg/.png/.pdf only.');
                fileInput.value = '';
                return false;
            }
        }
        
        let fileSize_mb = (fileSize / 1024 / 1024).toFixed(2);
        
        if(fileSize_mb > allowedTotalSize) {
            alert('The combined size of all files should not exceed '+allowedTotalSize+' MB.');
            fileInput.value = '';
            return false;
        }
    }
}

// Multiple files upload handler function
function UploadFiles(){
    const fileInput = document.getElementById('file_input');
    let fileInput_length = fileInput.files.length;

    const formData = new FormData();
    if (fileInput_length > 0) {
        for (var i = 0; i < fileInput_length; i++) {
            formData.append("files[]", fileInput.files[i]);
        }
    }

    const messageContainer = document.querySelector("#status-msg");
    messageContainer.innerHTML = '';
    const btnContainer = document.querySelector("#uploadBtn");
    btnContainer.disabled = true;
    btnContainer.innnerHTML = 'Uploading...';

    fetch("upload_init.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status == 1) {
            messageContainer.innerHTML = '<div class="alert alert-success">'+data.msg+'</div>';
        } else {
            messageContainer.innerHTML = '<div class="alert alert-danger">'+data.error+'</div>';
        }
        btnContainer.disabled = false;
        btnContainer.innnerHTML = 'Upload';

        setTimeout(function () {
            messageContainer.innerHTML = "";
        }, 5000);
    })
    .catch(console.error);
}
</script>

Upload Multiple Files using PHP (upload_init.php)

This file is loaded by the fetch() method (from the client side) to perform the multiple file upload using PHP.

  • $allowTypes – The file types that are allowed to be uploaded.
  • $uploadDir – Folder path where the files will be stored on the server.
  • Retrieve the multiple files data using the $_FILES method in PHP.
  • Loop through the files and access each file’s data from multiple files.
  • Check the file extension to allow certain file formats (PDF and Image) to upload.
  • Upload multiple files to the server using the move_uploaded_file() function in PHP.
  • Return response to the client-side script.
<?php 
$allowTypes 
= array('jpg','png','jpeg','pdf'); 
$uploadDir 'uploads/';

if(!empty(
$_FILES['files']['name'])){ 
    
$uploaded_files_str '';
    foreach(
$_FILES['files']['name'] as $key=>$val){
        
// File upload path
        
$fileName basename($_FILES['files']['name'][$key]); 
        
$targetFilePath $uploadDir.$fileName
            
        
// Check whether file type is valid
        
$fileType pathinfo($targetFilePathPATHINFO_EXTENSION); 
        if(
in_array($fileType$allowTypes)){ 
            
// Upload file to server
            
if(move_uploaded_file($_FILES['files']["tmp_name"][$key], $targetFilePath)){
                
$uploaded_files_str .= $fileName.', ';
            }
        }
    } 
    
$uploaded_files_str trim($uploaded_files_str', ');

    
$output = [
        
'status' => 1,
        
'msg' => 'Files have been uploaded successfully!<br/>Uploaded Files: {'.$uploaded_files_str.'}'
    
];
    echo 
json_encode($output);
}else{
    echo 
json_encode(['status' => 0'error' => 'Please select files to upload!']);
}

?>

Ajax File Upload with Form Data using PHP

Conclusion

Here we demonstrate a simple method to upload multiple files with JavaScript. You don’t need any third-party dependancy such as jQuery to upload files to the server. Allow the user to upload multiple images or files without page refresh using JavaScript. This example provides a user-friendly way to upload multiple files to the server with JavaScript using PHP. You can also enhance the functionality of this JavaScript multiple file upload script as needed.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up