The most commonly utilised feature of the online application is file or image upload. When you wish to allow a user to upload a file to your server, the file upload functionality is useful. Using PHP and HTML file input fields, you may easily upload a file. In most circumstances, the online application only permits one file to be uploaded at a time. However, if you want the user to be able to submit several files, uploading them all at once will give a wonderful user interface.
You can upload many photos at once using PHP. However, you may give a user-friendly interface that allows users to submit many photographs with a single click without having to refresh the page. Using jQuery and Ajax, the photos may be uploaded without reloading the page. Using jQuery Ajax and PHP, we’ll show you how to upload many images without refreshing the page in this article. Using jQuery and PHP, the example code demonstrates the Ajax multiple picture upload procedure.
Uploading Files Form (index.html)
This file is responsible for selecting numerous pictures and sending Ajax requests.
Create an HTML form with a file input box so that the user can choose numerous files.
The method=”post” and enctype=”multipart/form-data” attributes must be present in the form> tag.
The type=”file” property and multiple attributes must be included in the input> tag.
<div class="upload-div">
<!-- File upload form -->
<form id="uploadForm" enctype="multipart/form-data">
<label>Choose Images</label>
<input type="file" name="images[]" id="fileInput" multiple >
<input type="submit" name="submit" value="UPLOAD"/>
</form>
<!-- Display upload status -->
<div id="uploadStatus"></div>
</div>
Define a DIV element on the web page that will be used to display the submitted photographs in a gallery view.
<!-- Gallery view of uploaded images -->
<div class="gallery"></div>
The jQuery and Ajax libraries will be needed to upload files, so include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The following jQuery code uses Ajax to transfer the data from the selected photos to the server-side script.
The data from the selected files is communicated to the server-side script (upload.php) using jQuery and Ajax when the form is submitted.
The uploaded picture data is retrieved using the FormData object.
The upload status is displayed to the user based on the response, and the uploaded images are appended to the specified element.
The MIME type of the selected files will also be verified, limiting the user to just uploading images.
<script>
$(document).ready(function(){
// File upload via Ajax
$("#uploadForm").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$('#uploadStatus').html('<img src="images/uploading.gif"/>');
},
error:function(){
$('#uploadStatus').html('<span style="color:#EA4335;">Images upload failed, please try again.<span>');
},
success: function(data){
$('#uploadForm')[0].reset();
$('#uploadStatus').html('<span style="color:#28A74B;">Images uploaded successfully.<span>');
$('.gallery').html(data);
}
});
});
// File type validation
$("#fileInput").change(function(){
var fileLength = this.files.length;
var match= ["image/jpeg","image/png","image/jpg","image/gif"];
var i;
for(i = 0; i < fileLength; i++){
var file = this.files[i];
var imagefile = file.type;
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
$("#fileInput").val('');
return false;
}
}
});
});
</script>
Using PHP to Upload Multiple Images (upload.php)
The Ajax request calls the upload.php file, which uses PHP to perform the image upload process.
Using the PHP $_FILES function, get the pictures data from the uploaded data.
Using PHP’s move uploaded file() method, post the photos to the server.
Create an HTML view using the photographs you’ve uploaded.
<?php
if(!empty($_FILES['images'])){
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Store images on the server
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
$images_arr[] = $targetFilePath;
}
}
}
// Generate gallery view of the images
if(!empty($images_arr)){ ?>
<ul>
<?php foreach($images_arr as $image_src){ ?>
<li><img src="<?php echo $image_src; ?>" alt=""></li>
<?php } ?>
</ul>
<?php }
}
?>
Using PHP, you may provide a preview of the selected photographs without having to submit them to the server.
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Display images without storing in the server
$img_info = getimagesize($_FILES['images']['tmp_name'][$key]);
$images_arr[] = "data:".$img_info["mime"].";base64,".base64_encode(file_get_contents($_FILES['images']['tmp_name'][$key]));
}
}
Note :
We’ve shown you how to use Ajax and PHP to upload numerous photos. You can simply upload numerous files/images without using a jQuery plugin by using our sample script. The Ajax multiple file upload functionality is quite beneficial when you want to allow the user to upload several images. You may utilise Drag and drop file upload with Dropzone JS and PHP to make multiple picture upload more user-friendly.