小编典典

如何上传文件夹中的所有图片

php

尝试从
服务器端的文件夹目标文件夹上传所有图像是test
图像的目标格式是uniqid().jpg

问题 - 服务器端的结果数组似乎是空的

<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);
}

阅读 155

收藏
2022-07-25

共1个答案

小编典典

您正在传递一个fd.append不正确的 FileList 对象,您必须遍历列表并单独添加每个文件。

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
  });
});

您使用的文件数组不正确,请参阅here

$arr = $_FILES['flist'];   
foreach($arr['tmp_name'] as $tempname){
    $uniq = uniqid();
    $img = imagecreatefromjpeg($tempname);
    $targ = 'test/' . $uniq . '.jpg';
    imagejpeg($img, $targ);
}
2022-07-25