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

使用Strapi上传图片遇400错误:Files are empty,求排查

解决Strapi上传图片提示“Files are empty”的400错误

你的问题核心是Strapi的文件上传接口要求请求体必须是FormData格式,而你直接传递了File数组,不符合接口的参数要求,因此返回400错误。以下是具体的排查和修复步骤:

问题分析

Strapi的/api/upload接口默认接收multipart/form-data类型的请求,且文件需要通过files字段传递(字段名可在Strapi后台配置中修改)。你当前直接将File数组作为请求体发送,接口无法识别,所以提示“Files are empty”。

另外补充一个小细节:你在onChange中调用setFileArrayForUpload后立即console.log(fileArrayForUpload),由于React的setState是异步操作,这里打印的是更新前的旧值,并非当前选中的文件。

修复代码

1. 修改文件上传逻辑(handleCreateSubmit)

需要将File数组包装成FormData后再发送请求,并且如果需要将上传的图片关联到产品,要把返回的文件ID添加到产品创建的参数中:

const [createProduct] = useMutation(CREATE_PRODUCT);

const handleCreateSubmit = useCallback(async () => {
  // 创建FormData对象,包装上传文件
  const formData = new FormData();
  fileArrayForUpload.forEach(file => {
    // 字段名'files'是Strapi上传接口的默认要求
    formData.append('files', file);
  });

  // 发送上传请求,指定Content-Type为multipart/form-data
  const res = await HTTP_CLIENT.post('/api/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
  console.log('上传结果:', res);

  // 提取上传后文件的ID,用于关联到产品
  const uploadedFileIds = res.data.map(file => file.id);
  
  await createProduct({
    variables: {
      data: {
        reference: reference,
        description: description,
        price: {
          displayPrice: currency,
          numericPrice: numericPrice,
        },
        category: selectedCategory,
        // 假设你的产品模型有images字段关联上传文件,这里传入文件ID数组
        images: uploadedFileIds
      },
    },
    onCompleted: handleSucessSubmit,
    onError: handleErrorSubmit,
  });
}, [
  reference,
  description,
  currency,
  numericPrice,
  selectedCategory,
  fileArrayForUpload,
]);

2. 修正input组件的日志输出

将console.log(fileArrayForUpload)改为打印当前选中的临时变量,避免异步状态的误导:

<input
  ref={inputRef}
  accept="image/*"
  type="file"
  multiple
  id="select-image"
  style={{ display: 'none' }}
  onChange={(e) => {
    if (!e.target.files) return;
    const selectedFiles = Array.from(e.target.files);
    const dataUrls = selectedFiles.map((file) =>
      URL.createObjectURL(file),
    );
    setFileArrayForUpload(selectedFiles);
    // 打印当前选中的文件,而非异步更新后的状态
    console.log('选中的文件:', selectedFiles);
    setImageUrlArray((prevImages) => [...prevImages, ...dataUrls]);
  }}
/>
<label htmlFor="select-image">
  <IconButton color="primary" component="span">
    <FileUploadIcon fontSize="large" />
  </IconButton>
</label>

关键注意事项

  • 确保Strapi后台已正确配置文件上传权限,且产品模型的关联字段(如images)已设置为与上传文件的关联关系
  • 部分HTTP客户端(如Axios)会自动识别FormData并设置正确的Content-Type,但手动指定能避免兼容性问题
  • 上传成功后必须将文件ID关联到产品,否则图片不会与产品绑定

内容的提问来源于stack exchange,提问作者Miguel Ângelo Freitas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:07:34