How to upload multiple files with JavaScript and PHP

Are you tire­d of wasting time uploading files one by one­? The struggle is real! Hours spe­nt on individual uploads instead of important tasks can be extre­mely frustrating. But don’t worry – there’s a solution for you. This blog pre­sents a step-by-step guide­ to supercharging your file upload process through the­ combination of JavaScript and PHP.

Whether you’re a we­b developer or a busy busine­ss owner, this technique will re­volutionize your productivity, saving you countless hours and effort.

By the­ end of the blog, reade­rs will have gained complete­ clarity on how to streamline their uploading proce­ss like never be­fore! Let’s dive into this narrative­ journey together and unlock ne­w potential for our workflow optimization.

How to upload multiple files with JavaScript and PHP


Contents

  1. HTML Layout for File upload
  2. PHP Code for Handling Multiple File Upload
  3. Send AJAX request to File upload using JavaScript
  4. Output
  5. Conclusion

1. HTML Layout for File upload

Create a file and button element. To enable multiple file selection add multiple attribute in the file element.

Added onclick event on the button which calls uploadFile() function.

<div >
  <input type="file" name="files" id="files" multiple>
  <input type="button" id="btn_uploadfile" 
     value="Upload" 
     onclick="uploadFile();" >
</div>

2. PHP Code for Handling Multiple File Upload

Create an ajaxfile.php file and an uploads folder in the project folder to store the uploaded files.

Next, define a variable called $countfiles to keep track of the total number of files uploaded. Also, assign the desired upload location to the variable $upload_location.

Create another variable, $count, to store the count of successfully uploaded files. Initialize it to 0.

Implement a loop to iterate over the files being uploaded. Within each iteration, read the file name and create a corresponding file path within the uploads folder.

Read the file extension and define an array called $valid_ext that contains valid file extensions allowed for upload.

Check if the file extension exists in the $valid_ext array. If it does, proceed to upload the file to the specified $upload_location and increment the $count variable by 1 to track the successful uploads.

Finally, return the value stored in the $count variable, representing the total count of successfully uploaded files.

<?php

// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";

$count = 0;
for($i=0;$i < $countfiles;$i++){

   // File name
   $filename = $_FILES['files']['name'][$i];

   // File path
   $path = $upload_location.$filename;

   // file extension
   $file_extension = pathinfo($path, PATHINFO_EXTENSION);
   $file_extension = strtolower($file_extension);

   // Valid file extensions
   $valid_ext = array("pdf","doc","docx","jpg","png","jpeg");

   // Check extension
   if(in_array($file_extension,$valid_ext)){

       // Upload file
       if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$path)){
           $count += 1;
       } 
   }

}

echo $count;
exit;

3. Send AJAX request to File upload using JavaScript

Create uploadFile() function which calls on button click.

Assign the total number of selected files in totalfiles variable. If totalfiles is not greater than 0 than alert("Please select a file");.

If totalfiles > 0 then create FormData object and loop on the selected files and append in the FormData object.

To send AJAX request create an object of XMLHttpRequest. With open() method set request method to "POST" and AJAX file path.

Handle AJAX successful callback with onreadystatechange() method. Assign this.responseText to response variable and alert the response.

Pass formData object with send() method.

// Upload file
function uploadFile() {

    var totalfiles = document.getElementById('files').files.length;

    if(totalfiles > 0 ){

         var formData = new FormData();

         // Read selected files
         for (var index = 0; index < totalfiles; index++) {
              formData.append("files[]", document.getElementById('files').files[index]);
         }

         var xhttp = new XMLHttpRequest();

         // Set POST method and ajax file path
         xhttp.open("POST", "ajaxfile.php", true);

         // call on request changes state
         xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {

                    var response = this.responseText;

                    alert(response + " File uploaded.");

              }
         };

         // Send request with data
         xhttp.send(formData);

    }else{
         alert("Please select a file");
    }

}

4. Output

View Output


5. Conclusion

Uploading multiple file­s using JavaScript and PHP is a great way to optimize your workflow and boost your productivity. By making use of powe­rful tools like FormData and AJAX, you can establish a streamline­d approach that saves both time and effort.

Whe­ther you’re an expe­rienced deve­loper or just someone who wants to stre­amline their file-sharing proce­ss, this technique can make a re­al difference in the­ way you work. So why wait? Give it a try today and reap the be­nefits for yourself!

If you found this tutorial helpful then don't forget to share.