I would like to send Javascript array containing files to PHP using AJAX
The following are 3 files that I want to send to the php side. (These outputs come from console.log(document.getElementById("id").files[0]
);
File { name: "img1.svg", lastModified: 1641853737982, webkitRelativePath: "", size: 2506, type: "image/svg+xml" }
File { name: "img2.svg", lastModified: 1641853677323, webkitRelativePath: "", size: 1060, type: "image/svg+xml" }
File { name: "img3.svg", lastModified: 1641853656789, webkitRelativePath: "", size: 1845, type: "image/svg+xml" }
In this case there are 3 files (There can be more or less than that).
The 3 files are in a variable arrFiles
.
So console.log(arrFiles) outputs:
Array [ File, File, File]
JQuery file
var form_data = new FormData();
var arrFiles = JSON.stringify(arrFiles)
form_data.append("imgs", arrFiles);
$.ajax({
url:url,
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
alert(data);
}
});
php file
if(isset($_POST["imgs"])){
//Would like to handle each image separately.
$imgs = json_decode($_POST['imgs']);
//May be something like :
foreach($_POST["imgs"] as $img){
$movePath = "images/".$img['name'];
move_uploaded_file($img["tmp_name"], $movePath);
}
return;
}
Is there a way to handle this ?