Upload Multiple Images without Page Refresh using jQuery Ajax and PHP

File or image upload is the most used functionality for the web application. Generally, the file upload functionality is useful when you want to allow the user to upload the file to your server. You can easily upload file using PHP and HTML file input field. Most cases, the web application allows uploading a single file at a time. But if you want to allows the user to upload multiple files, upload all files at once will provide a great user interface.

Using PHP, you can upload multiple images at once. But you can also provide a user-friendly interface to upload multiple images on a single click without page refresh. The images can be uploaded without page reload using jQuery and Ajax. In this tutorial, we will show you how to upload multiple images without page refresh using jQuery Ajax and PHP. The example code shows the Ajax multiple images upload process using jQuery and PHP.

Files Upload Form (index.html)

This file handles the multiple images selection, Ajax request sending process.

HTML Code:
Create an HTML form with a file input field that allows the user to select multiple files.

  • The <form> tag must contain the method="post" and enctype="multipart/form-data" attributes.
  • The <input> tag must contain type="file" and multiple 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 in the web page where the uploaded images will be displayed in a gallery view.

<!-- Gallery view of uploaded images --> 
<div class="gallery"></div>

JavaScript Code:
To upload files, the jQuery and Ajax will be used, 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 sends the selected images data to the server-side script via Ajax.

  • On form submission, the selected files data is sent to the server-side script (upload.php) using jQuery and Ajax.
  • The FormData object is used to retrieve the submitted images data.
  • Based on the response, the upload status is shown to the user and the uploaded images are appended to the specified element.
  • Also, 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 PHP $_FILES method.
  • Upload the images to the server using move_uploaded_file() function in PHP.
  • Generate 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]));
    }
}

Conclusion

Here we provided a simple way to upload multiple images with Ajax and PHP. Using our example script, you can easily upload multiple files/images without any jQuery plugin. When you want to allow the user to upload multiple images, the Ajax multiple files upload functionality is very useful. To make multiple images upload functionality more user-friendly, you can use Drag and drop file upload using Dropzone JS and PHP.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Rudi Said...
  2. Coinextend Said...

Leave a reply

keyboard_double_arrow_up