PHP AJAX Multiple Image Upload using jQuery

This tutorial describes about how to upload multiple images using PHP via jQuery AJAX. It will be easy to follow this tutorial if you read single image upload. We will have multiple file input options in a form. Images to be uploaded will be chosen using those input fields. Then using jQuery AJAX the multiple images will be uploaded to the backend. The backend can be a database or a folder in disk as per our choice.

View Demo

Multiple Input File

In this example, we are having multiple file type input in our form. The HTML form is,

<form id="uploadForm" action="upload.php" method="post">
<div id="gallery">No Images in Gallery</div>
<div id="uploadFormLayer">
<p class="txt-subtitle">Upload Multiple Image:</p>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<p><input type="submit" value="Submit" class="btnSubmit" /><p>
</div>
</form>

Instead of that, we can add dynamic file type input to our form on event basis.

jQuery AJAX Call for Multiple Image Upload

The jQuery script is similar for both single and multiple image upload. That is,

$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
	url: "upload.php",
	type: "POST",
	data:  new FormData(this),
	contentType: false,
	cache: false,
	processData:false,
	success: function(data){
	$("#gallery").html(data);
	},
	error: function(){} 	        
});
}));

Image File Iteration in PHP

In PHP file, we are iterating input file array and upload it to the target location. After that, it response with image markup to be displayed to the target selector as the AJAX success response.

<?php
if(is_array($_FILES)) {
foreach ($_FILES['userImage']['name'] as $name => $value){
if(is_uploaded_file($_FILES['userImage']['tmp_name'][$name])) {
$sourcePath = $_FILES['userImage']['tmp_name'][$name];
$targetPath = "images/".$_FILES['userImage']['name'][$name];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>" width="150px" height="180px" />
<?php
}}}}
?>

php-ajax-multiple-image-upload

Live DemoDownload

This jQuery code tutorial was published on October 6, 2014.

↑ Back to Top