Ajax - PHP - Upload nhiều tập tin

Upload nhiều tập tin sử dụng Ajax

Trong thư mục chúng ta tạo thêm thư mục uploads

tạo tập tin ajax_upload.js

// JavaScript Document
$(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">');
       }

     }
   });

});

});

Tạo tập tin 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;

Tạo tập tin index.php

 <!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Ajax File Upload with jQuery and PHP</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<script src="ajax_upload.js"></script>
<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>
</body></html>