In this tutorial, we will learn How to Upload Multiple Images using Javascript Ajax and PHP with an example.

Upload Multiple Files using JavaScript Ajax and PHP
Contents
HTML
Creating a index.html
file.
Create a one file type input element, for selecting multiple files add multiple
Attribute. also assigned a unique ID id="files"
in it.
Create a button, Call a uploadFile()
function on clicking on it. we will call an AJAX in uploadFile()
function.
<form method="post" enctype="multipart/form-data">
<input type="file" name="upload[]" id="files" multiple>
<button type="button" id="upload" name="uploadBtn" onclick="uploadFile();"> Upload</button>
</form>
<div id='preview'>
</div>
Javascript
Create an FormData
object and count total files are been selected. Loop on the selected files and append them in form_data
.
we use the open()
method of the XMLHttpRequest
object to send a request to the server and Handle AJAX successful callback with onreadystatechange()
method.
We will render uploaded images on the front-end, in <div class='preview' >
element.
Multiple Files upload using JavaScript – Script
<script type="text/javascript">
function uploadFile() {
var formData = new FormData();
// Read selected files
var totalFiles = document.getElementById('files').files.length;
for (var i = 0; i < totalFiles; i++) {
formData.append("files[]", document.getElementById('files').files[i]);
}
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;
const filesArray = JSON.parse(response);
var html = '';
for (var index = 0; index < filesArray.length; index++) {
var src = filesArray[index];
html += '<img src="' + src + '" width="200px;" height="200px">';
}
document.getElementById("preview").innerHTML = html;
}
};
// Send request with data
xhttp.send(formData);
}
</script>
PHP
Create a ajaxfile.php
file.
First, we Count the total files, Loop on the files.
Then we initialize $valid_ext
Array with valid image extensions. Check if the file extension exists in $valid_ext
Array. If it exists then upload the file and initialize $files_arr
Array with $path
.
Return $files_arr
in JSON format for rendering uploaded images on the frontend.
// Count total files
$countFiles = count($_FILES['files']['name']);
// Upload directory
$upload_location = "upload/";
// To store uploaded files path
$files_arr = array();
//Loop through each file
for ($i = 0; $i < $countFiles; $i++) {
if (isset($_FILES['files']['name'][$i]) && $_FILES['files']['name'][$i] != '') {
// Get the file name
$filename = $_FILES['files']['name'][$i];
// Get extension
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Valid image extension
$valid_ext = array("png", "jpeg", "jpg");
// Check extension
if (in_array($ext, $valid_ext)) {
// Setup The destination of the moved file.
$path = $upload_location . $filename;
// Upload file
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $path)) {
$files_arr[] = $path;
}
}
}
}
echo json_encode($files_arr);
Be First to Comment