You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多图上传后Controller无法读取文件问题求助

问题原因及修复方案

核心问题点

1. FormData 文件添加方式错误

你的imageUpload函数里直接把FileList对象整体添加到FormData中,不符合FormData规范,后端无法正确解析:

formData.append(name, dataRefs.files); // 错误:直接传入FileList

正确做法是遍历每个文件,逐个添加:

// 遍历文件列表,逐个添加到FormData
for (const file of dataRefs.files) {
  formData.append(name, file);
}

2. 后端读取的键名不匹配

前端第一个文件输入框的data-post-name值是image_background,但你后端用img_name读取,两者完全不对应。JS里是用data-post-name的值作为FormData的键,所以后端应该用$_FILES['image_background']来读取,而非img_name。

3. 文件上传请求未指定正确的后端地址

你的HTML输入框没有设置data-post-url属性,导致imageUpload函数里const url = dataRefs.input.getAttribute('data-post-url');拿到null,函数直接终止,根本没发送上传请求!

需要给input加上data-post-url属性,指向你的controller地址:

<input id="upload_image_background" 
       data-post-url="Controller/createadcontroller.php" 
       data-post-name="image_background" 
       name="img_name" 
       class="position-absolute invisible" 
       type="file" 
       multiple accept="image/jpeg, image/png, image/svg+xml" />

4. 表单缺少enctype属性(可选补充)

虽然你用fetch发送请求而非直接提交表单,但如果后续有表单提交需求,form标签必须加上enctype="multipart/form-data"才能正确上传文件:

<form action="Controller/createadcontroller.php" method="post" enctype="multipart/form-data">

修复后的关键代码片段

修复后的imageUpload函数

const imageUpload = dataRefs => {
  if (!dataRefs.files || !dataRefs.input) return;

  const url = dataRefs.input.getAttribute('data-post-url');
  if (!url) return;

  const name = dataRefs.input.getAttribute('data-post-name');
  if (!name) return;

  const formData = new FormData();
  // 遍历文件逐个添加
  for (const file of dataRefs.files) {
    formData.append(name, file);
  }

  fetch(url, {
    method: 'POST',
    body: formData
    // 不要手动设置Content-Type,浏览器会自动处理
  })
  .then(response => response.json())
  .then(data => {
    console.log('posted: ', data);
    if (data.success === true) {
      previewFiles(dataRefs);
    } else {
      console.log('上传失败: ', data)
    }
  })
  .catch(error => {
    console.error('请求错误: ', error);
  });
}

后端读取示例(针对多文件上传)

因为input设置了multiple,后端需要遍历$_FILES['image_background']获取所有文件:

// 检查是否有文件上传
if(isset($_FILES['image_background'])) {
  // 遍历所有上传的文件
  for($i=0; $i<count($_FILES['image_background']['name']); $i++){
    echo '文件名: ' . $_FILES['image_background']['name'][$i] . '<br>';
    // 后续可添加文件保存等逻辑
  }
} else {
  echo '没有检测到文件';
}

内容的提问来源于stack exchange,提问作者Davidito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:42:02