AJAX HTML Javascript jQuery PHP Example MORE Videos New
Need a Website Or Web Application Contact : +91 9437911966 (Whatsapp) Note: Paid Service

How to Upload multiple file using ajax, jQuery, PHP and MySQl


index.php

<style type="text/css">
#preview img{
   margin: 5px;
}
</style>
<form method='post' action='' enctype="multipart/form-data">
   <input type="file" id='files' name="files[]" multiple><br>
   <input type="button" id="submit" value='Upload'>
</form>

<!-- Preview -->
<div id='preview'></div>

$(document).ready(function(){

$('#submit').click(function(){

   var form_data = new FormData();

   /* Read selected files */
   var totalfiles = document.getElementById('files').files.length;
   for (var index = 0; index < totalfiles; index++) {
      form_data.append("files[]", document.getElementById('files').files[index]);
   }

   /* AJAX request */
   $.ajax({
     url: 'ajaxfile.php', 
     type: 'post',
     data: form_data,
     dataType: 'json',
     contentType: false,
     processData: false,
     success: function (response) {

       for(var index = 0; index < response.length; index++) {
         var src = response[index];

         /* Add img element in <div id='preview'> */
         $('#preview').append('<img src="'+src+'" width="200px;" height="200px">');
       }

     }
   });

});

});

ajaxfile.php

<?php
/* Count total files */
$countfiles = count($_FILES['files']['name']);

/* Upload directory */
$upload_location = "uploads/";

/* To store uploaded files path */
$files_arr = array();

/* Loop all files */
for($index = 0;$index < $countfiles;$index++){

   if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
      /* File name */
      $filename = $_FILES['files']['name'][$index];

      /* Get extension */
      $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

      /* Valid image extension */
      $valid_ext = array("png","jpeg","jpg");

      /* Check extension */
      if(in_array($ext, $valid_ext)){

         /* File path */
         $path = $upload_location.$filename;

         /* Upload file */
         if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
            $files_arr[] = $path;
         }
      }
   }
}

echo json_encode($files_arr);
die;