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

React TypeScript中无法向FormData添加文件的技术问题

解决React+TypeScript中FormData添加File报错的问题

报错原因

你的imageFile状态未指定类型,TypeScript默认推断其为unknown,而FormData.append()的第二个参数要求是Blob | string | undefined,类型不匹配导致报错。

解决方案

  1. 为useState指定明确类型
    将状态声明改为File | undefined类型,明确表示它要么是File对象,要么未定义:

    const [imageFile, setImageFile] = React.useState<File | undefined>();
    
  2. 添加非空校验(可选但推荐)
    在提交时先判断imageFile是否存在,避免空值传递:

    const handleOnSubmit = (values: Picture) => {
      if (!imageFile) return;
      const formData = new FormData();
      formData.append("formFile", imageFile);
      productImageMutation({ data: formData });
    };
    

完整修正代码

const [imageFile, setImageFile] = React.useState<File | undefined>();
const [productImageMutation, productImageMutationResult] = useAddProductImageMutation();

const handleUploadClick = (e: React.ChangeEvent<HTMLInputElement>) => {
  const file = e.target.files?.[0];
  if (file) setImageFile(file);
};

const handleOnSubmit = (values: Picture) => {
  if (!imageFile) return;
  const formData = new FormData();
  formData.append("formFile", imageFile);
  productImageMutation({ data: formData });
};

另外,建议把handleUploadClick的参数类型从any改为React.ChangeEvent<HTMLInputElement>,让类型检查更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:40:32