trying to upload all images from a folder
destination folder on server side is test
destination format for images is uniqid().jpg
problem - seems resulting array on server side is empty
<input type='file' class='inpfile' id='inpfo' webkitdirectory='' directory='' multiple='true'>
var inpfo = $('#inpfo');
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
fd.append('flist', flist);
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
contentType: 'multipart/form-data',
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
upload.php
$arr = $_FILES['flist']; //seems this is an empty array
foreach($arr as $el){
$tempname = $el['tmp_name'];
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}
CodePudding user response:
You are passing a FileList object fd.append
which is incorrect you have to loop through the list and add each file individually.
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
for (let i = 0; i < flist.length; i ){
fd.append('flist[]', flist[i]); // add [] to denote array
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
You're using the array of files incorrect, see here
$arr = $_FILES['flist'];
foreach($arr['tmp_name'] as $tempname){
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}