Upload multiple files using PHP, jQuery and AJAX

upload multiple files

Upload multiple files using PHP, jQuery and AJAX

How to upload multiple files using PHP, jquery and ajax?

The most common method to upload multiple files was using FORM/POST and it is done by Php. Php script can be used with HTML form to do the file upload. With Php file upload we can both single files and multiple files at a time. But it requires a page reloading, for more user-friendly without page refresh is better.

For this we can use jQuery Ajax as it not requires any page reload and it will display the imags which we uploaded instantly. So upload multiple files using jQuery Ajax and Php will be very easy and user-friendly for you.

Single and multiple file upload is available with jQuery Ajax.

Lets start our tutorial on Upload multiple files using jQuery,Ajax and php. Here I given as three sections Html, jQuery Ajax and Php. The Html part describes form elements for file upload with the code. jQuery Ajax describes code for fetching file details and php describes uploading files to folder.

HTML :

<!DOCTYPE html>
<html>
<head>
    <title>Upload Multiple files with jQuery Ajax and Php</title>
</head>
<body>
    <form method='post' action='' enctype="multipart/form-data">
        <input type="file" id='files' name="files[]" multiple><br>
        <input type="button" id="submit" value='Upload'>
    </form>
    <!-- for image preview -->
    <div id='preview'></div>
</body>
</html>

Explanation :

  1. Create a form with ‘POST’ method. The ‘enctype’ that is encoding type should be specified like ‘multipart/form-data’.
  2. Specify input type file with its name should be an array like : ‘files[]’. The ‘multiple’ attribute is mandatory as it for uploading multiple files.
  3. Specify button for form submission.
  4. The div with id ‘preview’ is for showing the uploaded file.

jQuery Ajax :

If we are using any jQuery script in our code, its mandatory to include jquery.js file. Please download or copy paste code from the below link and include just before your jquery script. You can copy paste the below link or just download the file.

Include jQuery.js file : <script src=”<script type="text/javascript"> $(document).ready(function(){ $('#submit').click(function(){ var form_data = new FormData(); // Read selected files var totalfiles = document.getElementById('files').files.length; for (var index = 0; index < totalfiles; index++) { form_data.append("files[]", document.getElementById('files').files[index]); } // AJAX request $.ajax({ url: 'upload.php', type: 'post', data: form_data, dataType: 'json', contentType: false, processData: false, success: function (response) { for(var index = 0; index < response.length; index++) { var src = response[index]; // Add img element in <div id='preview'> $('#preview').append('<img src="'+src+'" width="200px;" height="200px">'); } } }); }); }); </script>

Explanation :

  1. Call the ‘click’ event on clicking the submit button.
  2. ‘FormData()’ : This interface provides an easy way to construct a set of key/value pairs representing form fields with their values, which can then be easily sent using the XMLHttpRequest. In simple words all the form elements value will be in FormData() in the key/value pair form.
  3. Get the length of total files and put it in a for loop with the lenth as limit.
  4. Append each file values to form_data.
  5. In ajax request specify URL, type of posting the form data, form_data as the passing data, json as datatype.
  6. in success response append the files to the div with id preview.

PHP :

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

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

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

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

   // Get extension
   $ext = pathinfo($filename, PATHINFO_EXTENSION);

   // Valid image extension
   $valid_ext = array("png","jpeg","jpg");

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

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

     // Upload file
     if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
        $files_arr[] = $path;
     }
   }

}

echo json_encode($files_arr);
die;
?>

Explanation:

  1. Get the total count files to a variable by taking the count of array.
  2. Define the path or directory which we are going to upload the files.
  3. Declare an array to store the path of files.
  4. Loop through the array with count of files as the limit.
  5. Get the file names of each file. Here we are taking the original name, if you want the temporary names please use ‘temp_name’ instead of ‘name’.
  6. Get the extension of each file to check whether it is allowed or not. PATHINFO_EXTENSION will return the extension of files.
  7. Declare an array of allowed extensions and call the in_array() function to check the uploaded file extension is allowed or not.
  8. If allowed upload the file to the specified path with the help of move_uploaded_file().
  9. The json_encode() will encode the array and return to ajax success.

Note : In this tutorial I have included some bootstrap css to make good to see. I took the design from here Bootsnipp and did some css changes as follows;

<style type="text/css">
		body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8!important;
  height: 100vh;
}
#login .container #login-row #login-column #login-box {
  margin-top: 60px;
  max-width: 600px;
  height: 320px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
#login-box 
{
	min-height: 500px;
	height:auto;
	overflow-y: scroll;
}
	</style>

The preview div given just after closing the form.

Hope this tutorial for upload multiple files using Php, Jquery and ajax will help you to solve your trouble.

Leave a Reply

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

Back To Top