In this article we are going to talk about How to Upload Multiple Images without Page reload.
File or image upload is the very useful functionality for the web app. Normally, the file upload method is helpful when you want to authorize the user to upload the file or the image to your server. You can simply upload files or image in PHP. Mostly, the web app allows uploading a single file or image at a time. But if you want to allow the user to upload multiple files or images, upload all files at once will provide a good user interface.
Using PHP, you can upload multiple images or files at once. But you can also offer a catchy interface to upload multiple images or files on a single click without page reload. The images can be uploaded without page refresh using jQuery and Ajax in PHP. In this lesson, we will show you how to upload multiple images or files without page reload using jQuery Ajax in PHP. The sample code shows the Ajax multiple images or file upload process using jQuery in PHP.
How to Upload Multiple Images without Page reload using jQuery, Ajax and PHP
Files Upload Form file name (index.html)
This file controls the multiple image selection, Ajax request to php sending process.
HTML Code:
Create an HTML form with input field that allows the user to select multiple files.
- The tag must hold the method=”post” and enctype=”multipart/form-data” attributes.
- The tag must contain type=”file” and name with array [] and (multiple) attributes.
Specify a DIV in the web page where the uploaded images will be displayed in a gallery view design.
<!-- Gallery view of uploaded images -->
<div class="gallery"></div>
JavaScript Code:
For uploading files, the jQuery and Ajax will be used, we need to include the jQuery library .
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The next jQuery code will sends the uploaded images data to the server-side script via Ajax in php.
- On form submit, the selected images, record is sent to the server-side script file (upload.php) using jQuery and Ajax in php.
- The FormData object in jquery is used to fetch the submitted images images.
- Based on the response of php, the upload status is shown to the user and the uploaded data are appended to the specified HTML element.
- Also, the MIME type of the selected images will be validated and limit the user to upload only the 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>
Upload Multiple Images using PHP script (upload.php)
The upload.php file is called by the Ajax send request to handling the uploaded images process using PHP.
- Fetch the images record from posted data using PHP $_FILES method in upload.php file.
- Upload the images to the server using move_uploaded_file() function using PHP.
- Create an HTML view with the uploaded images.
<?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 }
}
?>
You can display a preview of the selected images without uploading to the server using PHP.
$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]));
}
}
Result
Here we provided an easy way to upload multiple images or files using Ajax with PHP. Using our sample script, you can easily upload multiple images/files without any jQuery plugin. When you want to authorize the user to upload multiple images/files, the Ajax multiple file upload method is very helpful. To make multiple images/files uploads method more user-friendly.
0 Comments