Upload Multiple Images using jQuery, Ajax and PHP

Image upload functionality is commonly used in web applications 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 functionality the user can upload images without reloading or refreshing the current page.

Generally, the 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 image upload without refreshing the page. There are two ways to display the preview of the uploaded image. 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 a file upload form and jQuery to post the images to the server-side for upload.

JavaScript Code:
The jQuery Form Plugin will be used to post file data via Ajax request. It allows you to upgrade the 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 and Ajax.

<!-- jQuery library -->
<script type="text/javascript" src="js/jquery.min.js"></script>

<!-- jQuery Form Plugin -->
<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 – A callback function that is invoked before form submission.
  • success – A callback function that is invoked after the response has been returned from the server.
  • error – A callback function that is invoked if an error occurred.
<script>
$(document).ready(function(){
    $('#uploadForm').ajaxForm({
        target:'#imagesPreview',
        beforeSubmit:function(){
            $('#uploadStatus').html('<img src="css/uploading.gif"/>');
        },
        success:function(){
            $('#images').val('');
            $('#uploadStatus').html('');
        },
        error:function(){
            $('#uploadStatus').html('<p>Upload failed! Please try again.</p>');
        }
    });
});
</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 Files and Images in CodeIgniter

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.
<?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($targetFilePathPATHINFO_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 }
}
?>

Create Dynamic Image Gallery with jQuery, PHP & MySQL

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 Image and Create Thumbnail using PHP

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

35 Comments

  1. Bee Said...
  2. Cynthia Said...
  3. Cynthia Said...
  4. Rajat Said...
  5. Patrik Iden Said...
  6. Karishma Pathak Said...
  7. Jovan Said...
  8. Dogum Gunu Pastasi Said...
  9. Shubham Said...
  10. Sam Smith Said...
  11. Nir Said...
  12. Steve Goerger Said...
  13. Naruto Said...
  14. FTE Said...
  15. Mohsin Khan Said...
  16. Ali Said...
    • CodexWorld Said...
  17. Taher Said...
  18. Msikkac Said...
  19. Satish Said...
  20. Zhujih Said...
  21. Bharathi Said...
  22. Umesh Chakor Said...
  23. Sehjad Said...
  24. Christian Said...
    • CodexWorld Said...
  25. Cykro Said...
    • CodexWorld Said...
  26. Sampath Said...
  27. Serkan Said...
    • CodexWorld Said...
  28. Boris Said...
  29. Kathy Said...

Leave a reply

keyboard_double_arrow_up