Upload multiple images with live preview using jQuery, Ajax, and PHP

  •  
  •  
  •  
  •  
  •  
  •  

Uploading files to a server is a common functionality of any web application. All of us know that HTML 5 allows us to upload multiple images using a single input. But how it actually works maybe you do not know. Also, sometimes you need to show the preview of the selected images or files before uploading them to the server. So, in this tutorial, I will guide you on how to upload multiple images with live preview using jQuery, Ajax, and PHP.

Also, you may be interested to read the following tutorials —

Upload multiple images with live preview using jQuery, Ajax, and PHP

HTML – Upload Multiple Images with Live Preview

let’s play with the code —

index.php

<div class="container">
  <form action="method" name="upload-file" id="form-upload-file" enctype="multipart/form-data">
    <div class="row">							
      <div class="col-lg-12">                    
                <div class="input-group">
                  <input type="file" name="upload_files[]" id="upload_files" class="form-control" value="Upload" multiple="multiple">&nbsp;
                  <span class="input-group-btn">
                    <button type="submit" name="submit" id="submit" class="btn btn-primary" type="button">Upload!</button>
                  </span>
                </div>
            </div>
      <div class="col-lg-12 text-center" id="preview_file_div"><ul></ul></div>
    </div>
  </form>
</div>

Here in the above HTML code, you can see that there are one input file element and one submit button. I used multiple=”multiple” attribute within the input file element so that users can choose multiple files at once. preview_file_div div will display the selected images or files before uploading them to the server. Also, you can remove any images or files from the preview if you want.

JS – Upload Multiple Images with Live Preview

preview.js

$(function () {

    var input_file = document.getElementById('upload_files');
    var deleted_file_ids = [];
    var dynm_id = 0;



    $("#upload_files").change(function (event) {
        var len = input_file.files.length;
        $('#preview_file_div ul').html("");
        
        for(var j=0; j<len; j++) {
            var src = "";
            var name = event.target.files[j].name;
            var mime_type = event.target.files[j].type.split("/");
            if(mime_type[0] == "image") {
              src = URL.createObjectURL(event.target.files[j]);
            } else if(mime_type[0] == "video") {
              src = 'icons/video.png';
            } else {
              src = 'icons/file.png';
            }
            $('#preview_file_div ul').append("<li id='" + dynm_id + "'><div class='ic-sing-file'><img id='" + dynm_id + "' src='"+src+"' title='"+name+"'><p class='close' id='" + dynm_id + "'>X</p></div></li>");
            dynm_id++;
        }
    });



    $(document).on('click','p.close', function() {
        var id = $(this).attr('id');
        deleted_file_ids.push(id);
        $('li#'+id).remove();
        if(("li").length == 0) document.getElementById('upload_files').value="";
    });





    $("form#form-upload-file").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append("deleted_file_ids", deleted_file_ids);
        $.ajax({
              url: 'upload.php',
              type: 'POST',
              data: formData,
              processData: false, 
              contentType: false,
              
              success: function(data) {
                 $('#preview_file_div ul').html("<li class='text-success'>Files uploaded successfully!</li>");
                 $('#upload_files').val("");
              },
              error: function(e) {
                  $('#preview_file_div ul').html("<li class='text-danger'>Something wrong! Please try again.</li>");                    
              }    
        });
    });

});



The preview.js file contains three jQuery functions.

The first is change() function executes when users select images or files from the browse dialog box. Later based on the mime type of the files I created previews for each of them. If mime type is image/* I created the src from the following function URL.createObjectURL(event.target.files[j]);. If the file has video/* mime type then I simply showing a video icon. Rest of all are showing a file icon. And at the end of the function, I appended all of the previews to <ul> tag.

The second function that is click() function executes when users clicked on the close(x) icon of individual image previews. If you delete an image then its id will be stored in the deleted_file_ids array to prevent them from uploading on the server.

The third that is submit() function executes when users clicked on the submit button for multiple image uploading to the server. $.ajax({…}) function sends all the form data to the upload.php. On success or failure, it will display a message in place of the previews.

PHP – Upload Multiple Images with Live Preview

upload.php

<?php
if(isset($_FILES) && !empty($_FILES)) {
  $deleted_file_ids = array();
  if(isset($_POST['deleted_file_ids']) && !empty($_POST['deleted_file_ids'])) {
    $deleted_file_ids = explode(",", $_POST['deleted_file_ids']);
  }


  for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++) {
    if(!in_array($i, $deleted_file_ids)) {
      if($_FILES['upload_files']['name'][$i] != "") {
        $location = "uploaded-contents/".$_FILES['upload_files']['name'][$i];
        copy($_FILES['upload_files']['tmp_name'][$i], $location); 
      }
    }
  }
}
?>

In the above PHP code simply we run a for loop and checking if the i’s value is in the $deleted_file_id array or not. If no then we will upload it on the server otherwise not.

 

Live imgage preview before uploading to the server using jQuery, Ajax, and PHP

That’s all friends, Hope you enjoyed this tutorial. You can try the demo and download the complete source code on how to upload multiple images with live preview using jQuery, Ajax, and PHP from the below Demo and Download links.

If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial on how to upload multiple images with live preview using jQuery, Ajax, and PHP with others. Kindly subscribe Mitrajit’s Tech Blog to keep yourself updated with the upcoming tutorials.

 

About Mitrajit

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *