ต่อจากบทความที่แล้วจะเป็น เทคนิคการ Upload File ด้วย Javascript แบบ Single File สำหรับบทความนี้เป็นการประยุกต์ใช้งานเพิ่มเติมในการ Upload แบบ Multiple File
แก้ไข ไฟล์ index.php ดังนี้
<!DOCTYPE html> <html> <head> <style> body { margin:0px; height:100vh; } #center-image { height:100%; display:flex; align-items:center; justify-content:center; } .fimage { width:350px; padding:20px; } #preview{ width:100%; display:none; margin-bottom:30px; } #file1 { display:none; } .fimage label { display:block; padding:5px; text-align:center; background:green; color:#fff; text-transform:Uppercase; font-weight:800; cursor:pointer; } </style> </head> <body> <div id="center-image"> <div class="fimage"> <img id="preview"> <div id="placehere"></div> <label for="file1">Upload Image Multiple File</label> <input type="file" id="file1" name="files" accept="image/*" onchange="preview(event);" multiple> </div> </div> <script> function preview(event) { var totalFiles = event.target.files.length;//นับจำนวนไฟล์ที่เลือก var formData = new FormData(); if(totalFiles > 0){ for(var i = 0;i<totalFiles;i++){ formData.append("files[]", event.target.files[i]); let reader = new FileReader(); reader.onload = function() { var elem = document.createElement("img"); elem.setAttribute("src",reader.result);//แสดงไฟล์ภาพตัวอย่าง elem.setAttribute("height", "100"); elem.setAttribute("width", "100"); document.getElementById("placehere").appendChild(elem); }; reader.readAsDataURL(event.target.files[i]); } uploadFile(formData);// call function upload file } } function uploadFile(data){ let xhr = new XMLHttpRequest(); //creating new xhr object (AJAX) xhr.open("POST", "php/upload.php"); //sending post request to the specified URL xhr.send(data); //sending form data } </script> </body> </html>
ตัวอย่างไฟล์ upload.php
<?php
ini_set('upload_max_filesize', '20M');
ini_get('upload_max_filesize'), ", " , ini_get('post_max_size');
$file_name = $_FILES['file']['name']; //file name
$tmp_name = $_FILES['file']['tmp_name']; //temp_name of file
$file_up_name = time().$file_name; //making file name
$imgPath = "files/".$file_up_name;
move_uploaded_file($tmp_name,$imgPath); //moving file to the specified folder
//save image path to database
$servername = "mysql-database";
$username = "root";
$password = "456ASD#c";
$dbname = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$today = date("Y-m-d H:i:s");
$sql = "INSERT INTO `image`(`id`, `image_path`, `create_date`) VALUES (NULL,'$imgPath','$today')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>