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
JavaScript
x
23
23
1
<input type='file' class='inpfile' id='inpfo' webkitdirectory='' directory='' multiple='true'>
2
3
var inpfo = $('#inpfo');
4
5
inpfo.on('change', function(){
6
var flist = inpfo[0].files;
7
var fd = new FormData();
8
fd.append('flist', flist);
9
$.ajax({
10
url: 'upload.php',
11
type: 'POST',
12
data: fd,
13
async: false,
14
contentType: 'multipart/form-data',
15
success: function (data){
16
console.log(data); // Undefined array key "flist"
17
},
18
cache: false,
19
contentType: false,
20
processData: false
21
});
22
});
23
upload.php
JavaScript
1
9
1
$arr = $_FILES['flist']; //seems this is an empty array
2
foreach($arr as $el){
3
$tempname = $el['tmp_name'];
4
$uniq = uniqid();
5
$img = imagecreatefromjpeg($tempname);
6
$targ = 'test/' . $uniq . '.jpg';
7
imagejpeg($img, $targ);
8
}
9
Advertisement
Answer
You are passing a FileList object fd.append
which is incorrect you have to loop through the list and add each file individually.
JavaScript
1
20
20
1
inpfo.on('change', function(){
2
var flist = inpfo[0].files;
3
var fd = new FormData();
4
for (let i = 0; i < flist.length; i++){
5
fd.append('flist[]', flist[i]); // add [] to denote array
6
}
7
$.ajax({
8
url: 'upload.php',
9
type: 'POST',
10
data: fd,
11
async: false,
12
success: function (data){
13
console.log(data); // Undefined array key "flist"
14
},
15
cache: false,
16
contentType: false,
17
processData: false
18
});
19
});
20
You’re using the array of files incorrect, see here
JavaScript
1
8
1
$arr = $_FILES['flist'];
2
foreach($arr['tmp_name'] as $tempname){
3
$uniq = uniqid();
4
$img = imagecreatefromjpeg($tempname);
5
$targ = 'test/' . $uniq . '.jpg';
6
imagejpeg($img, $targ);
7
}
8