Upload Multiple Images using jQuery, Ajax and PHP

 


In a web application, image uploading is a common functionality that can be easily implemented in PHP. jQuery and Ajax are required with PHP, however, if image uploads without page refresh are desired. An image can be uploaded without reloading the page, making the web application more user-friendly. Uploading a file with Ajax doesn’t require a reload or refresh of the page.

When a file input field is used, only one image will be uploaded at a time. Nevertheless, your web application may require users to upload more than one image at the same time. We will demonstrate a method that uses jQuery, Ajax, and PHP to upload multiple images without requiring a page refresh. Multiple image uploads using Ajax allow the user to select multiple files at once and upload them all to the server with just one click.

In this example code, you will find out how to upload multiple images at once using jQuery, Ajax, and PHP without having to reload the page. This eliminates the need to reload the page when uploading multiple images. The uploaded image preview can be displayed one of two ways. You can show the uploaded images with or without stored in a directory of the server.

Multiple Files Upload Form

The HTML form to upload files will be created using jQuery, and the server-side upload will be done with HTML.

JavaScript

In order to post files data via Ajax, we will use the jQuery Form Plugin. AJAX allows us to modify an HTML file upload form. Utilizing jQuery Ajax for form submission, include the jQuery library and jQuery Form Plugin.

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

The ajaxForm method of jQuery Form Plugin prepares the HTML form for AJAX submission. Any $.ajax options can be passed in ajaxForm() function.

target – Specify the element(s) to update with the server response.
beforeSubmit – Callback function that invoked before form submission.
success – Callback function that invoked after the response has been returned from the server.
error – Callback function that invoked if an error occurred.

<script>
$(document).ready(function(){
    $('#uploadForm').ajaxForm({
        target:'#imagesPreview',
        beforeSubmit:function(){
            $('#uploadStatus').html('<img src="uploading.gif"/>');
        },
        success:function(){
            $('#images').val('');
            $('#uploadStatus').html('');
        },
        error:function(){
            $('#uploadStatus').html('Images upload failed, please try again.');
        }
    });
});
</script>

HTML

Make an HTML form that allows users to upload multiple images by adding a field to select them.

  • The tag must contain these attributes – method=”post” and enctype=”multipart/form-data”
  • The tag must contain type=”file” and multiple attributes.
<!-- images upload form -->
<form method="post" id="uploadForm" enctype="multipart/form-data" action="upload.php">
    <label>Choose Images</label>
    <input type="file" name="images[]" id="images" multiple >
    <input type="submit" name="submit" value="UPLOAD"/>
</form>

<!-- display upload status -->
<div id="uploadStatus"></div>

Upload Images Preview: Create a div with a target ID defined in the ajaxForm of Form Plugin API. This div will display the uploaded images.

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

Upload Multiple Images with PHP (upload.php)

Multiple images can be uploaded using PHP’s upload.php file, which renders the images in a gallery view.  

  • Specify the file upload path.
  • Get the file extension using pathinfo() function in PHP and check whether the user selects only the image files.
  • Upload images to the server using move_uploaded_file() function in PHP.
  • Generate gallery view of the uploaded images. This view will be shown in the target element of ajaxForm.
<?php
if(isset($_POST['submit'])){
    // 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 }
}
?>

Images can be uploaded and rendered without storing them on the server.

<?php
    $images_arr = array();
    foreach($_FILES['images']['name'] as $key=>$val){
        //display images without stored
        $extra_info = getimagesize($_FILES['images']['tmp_name'][$key]);
        $images_arr[] = "data:" . $extra_info["mime"] . ";base64," . base64_encode(file_get_contents($_FILES['images']['tmp_name'][$key]));
    }
?>

Conclusion

Through the use of jQuery, AJAX, and PHP we have made it possible to upload images without refreshing the page.

*

Post a Comment (0)
Previous Post Next Post