In this tutorial, I will tell you how to upload multiple images with image preview without refreshing page using PHP, jQuery and Ajax.
In this example, i have used jquery with jquery form plugins, using this plugins i am uploading files on server.
In my previous post, i told you about How to upload an image from a URL in PHP.
You will fine very short easy and useful script here to upload multiple images with preview.
We will show you images in two way. First i will show you on changed event using jquery without uploading files on server and second i will show you images after upload.
Create a HTML FileIn this step, i will create a html file first with name multiupload.html
and then create a section area for form and preview images.
I have defined a JavaScript method to preview images and i have calculated the file length to know how many files are going to preview.
- <html>
- <head>
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
- <script type="text/javascript" src="http://www.expertphp.in/js/jquery.form.js"></script>
- <script>
- function preview_images()
- {
- var total_file=document.getElementById("images").files.length;
- for(var i=0;i<total_file;i++)
- {
- $('#image_preview').append("<div class='col-md-3'><img class='img-responsive' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");
- }
- }
- </script>
- </head>
- <body>
- <div class="row">
- <form action="multiupload.php" method="post" enctype="multipart/form-data">
- <div class="col-md-6">
- <input type="file" class="form-control" id="images" name="images[]" onchange="preview_images();" multiple/>
- </div>
- <div class="col-md-6">
- <input type="submit" class="btn btn-primary" name='submit_image' value="Upload Multiple Image"/>
- </div>
- </form>
- </div>
- <div class="row" id="image_preview"></div>
- </body>
- </html>
In this step, we will create a PHP file multiupload.php
file that contains simple PHP codes to uploading and listng images view.
Before going to move file, create a directory 'images' with write permission so that you can upload files within this directory.
- <?php
- if(isset($_POST['submit_image']))
- {
- $images_array=array();
- foreach($_FILES['images']['name'] as $key=>$val){
- $uploadfile=$_FILES["images"]["tmp_name"][$key];
- $folder="images/";
- $target_file = $folder.$_FILES['images']['name'][$key];
- if(move_uploaded_file($_FILES["images"]["tmp_name"][$key], "$folder".$_FILES["images"]["name"][$key])){
- $images_array[] = $target_file;
- }
- }
- }
- if(!empty($images_array)){
- foreach($images_array as $src){ ?>
- <ul>
- <li >
- <img src="<?php echo $src; ?>">
- </li>
- </ul>
- <?php }
- }
- ?>