File or image upload is the maximum used functionality for the web application. Usually, the file upload functionality is useful when you want to permit the user to upload the file to your server. Therefore, you can effortlessly upload a file by using HTML and PHP file input fields. In many cases, the web application permits uploading a single file at a time. But, if you want to help the user to upload multiple files, then uploading all the files at once will provide an exceptional user interface.
By using PHP, you can upload multiple images at one time. But you may also offer a user-friendly interface to upload multiple images on a single click without page refresh. Therefore, you can upload the image without page reload using Ajax and jQuery. In this tutorial, we will explain to you how to upload multiple images without page refresh using jQuery Ajax and PHP. The sample code shows the Ajax multiple images upload process using jQuery and PHP.
Files Upload Form (index.html)
This file handles the process of selecting multiple images, sending Ajax requests.
HTML Code:
Make an HTML form. So, the file input field that permits the user to select multiple files.
- The <form> tag must contain the
method="post"
andenctype="multipart/form-data"
attributes. - The <input> tag must contain
type="file"
andmultiple
attributes.
<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 where you will display the uploaded images in a gallery view.
<!-- Gallery view of uploaded images --> <div class="gallery"></div>
SEE ALSO: Upload and Add Watermark to Image using PHP
JavaScript Code:
We have to use the jQuery and Ajax to upload images, include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The jQuery code, which is given below, will send the selected images data to the server-side script via Ajax.
- Firstly, on form submission, the selected files data is sent to the server-side script (
upload.php
) using jQuery and Ajax. - Secondly, you have to use the FormData object to retrieve the submitted images data.
- Based on the response, show the upload status to the user, and the uploaded images are appended to the specified element.
- At last, the MIME type of the selected files will be validated and restrict 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 (upload.php)
The upload.php
file is called by the Ajax request to handles the images upload process using PHP.
- Retrieve the images data from posted data using the PHP $_FILES method.
- You can use the move_uploaded_file() function in PHP to upload the image in the server.
- 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 show the preview of the selected images without uploading it 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])); } }
SEE ALSO: Multiple Image Upload with View, Edit and Delete in PHP
Conclusion
Firstly, we define a simple way to upload multiple images with Ajax and PHP. Secondly, by using our sample code script, you can upload multiple files/images without any jQuery plugin. So, when you want to let the user upload multiple images, the Ajax multiple files upload functionality is beneficial. At last, to make various images upload feature more user-friendly, you can use Drag and drop file upload using Dropzone JS and PHP.
Also, read our previous blog- Image Gallery CRUD with PHP and MySQL