Upload Multiple Images using jQuery, Ajax and PHP

Image upload functionality is commonly used in the web application and it can be easily implemented using PHP. But if you want to implement image upload functionality without page refresh, jQuery and Ajax are required with PHP. Upload image without page refresh provides a user-friendly interface for the web application. With Ajax file upload the user can upload images without reloading or refresh the current page.
Generally, file input field uploads a single image at a time. But in some cases, your web application requires allowing the user to upload multiple images at the same time. In this tutorial, we will show you how to upload multiple images without page refresh using jQuery, Ajax, and PHP. Ajax multiple image upload allows the user to select multiple image files at once and upload all the images to the server in a single click.
The example code helps you to upload multiple images at once without page refresh using jQuery, Ajax, and PHP. It simplifies the multiple images upload without refreshing the page. There are two ways to display the uploaded images preview. You can show the uploaded images with or without stored in a directory of the server.

Multiple Files Upload Form

We will use the HTML to create file upload form and the jQuery to post the images to the server-side for upload.
JavaScript Code:
The jQuery Form Plugin will be used to post files data via Ajax. It allows you to upgrade HTML file upload form to use AJAX. So, include the jQuery library and jQuery Form Plugin to submit the form with files for uploading using jQuery Ajax.
<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 Code:
Create an HTML form with an input field to allow the user to select multiple images they want to upload.
  • The <form> tag must contain these attributes – method="post" and enctype="multipart/form-data"
  • The <input> 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>
Uploaded Images Preview: Create div with target ID which is defined in ajaxForm of Form Plugin API. The uploaded images will be displayed in this div.
<!-- gallery view of uploaded images --> 
<div class="gallery" id="imagesPreview"></div>

Upload Multiple Images with PHP (upload.php)

The upload.php file process the multiple image upload using PHP and render the uploaded 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.
<?phpif(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 }
}?>
You can upload the images and render the preview of the images without stored 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

Here we have tried to make it simple to upload multiple images without page refresh using jQuery, Ajax, and PHP. You can also upload multiple images without any jQuery plugin using PHP. If you’re looking the advanced uploading feature in your web application, implement Drag and drop file upload using Dropzone JS and PHP.
Upload Multiple Images using jQuery, Ajax and PHP Upload Multiple Images using jQuery, Ajax and PHP Reviewed by Pakainfo on July 18, 2018 Rating: 5

No comments:

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers Bolante Idowu Alo died following altercation wit...

Powered by Blogger.