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

如何向ImageKit服务器POST文件?React上传遇400错误求助

问题:React上传文件到ImageKit时提示fileName参数缺失,但参数已存在

我已经完成React UI的多文件选择与上传功能,核心代码如下:

<input type='file' accept='image/*' id='selectFiles' multiple onChange={handleFileChange} />

选中的文件存储在状态变量中:

const [fileList, setFileList] = React.useState<FileList>();

我已确认文件存储正常,可通过预览DIV查看。按照ImageKit指引搭建了返回认证凭证的Auth端点,之后在useEffect中遍历fileList逐个上传文件到ImageKit服务器,但即使只传单个文件,也一直收到400错误,提示fileName参数缺失。我确认该参数并未缺失,怀疑问题出在file参数的传递上。关键代码(隐私信息已模糊处理)如下:

const uploadFile = async (file: File) => {
  try {
    const body = {
      file: file,
      publicKey: 'my_public_key',
      signature: 'imageKit_signature',
      expire: 'imageKit_expiry_value',
      token: 'imageKit_token',
      fileName: 'test123.jpg',
      useUniqueFileName: false,
      folder: userName,
      overwriteFile: false,
    };

    const response = await axios.post('https://upload.imagekit.io/api/v1/files/upload', body);
    console.log(response.status, response.data);
  } catch (err) {
    console.error(err);
  }
};

请问哪里出错了?


解答

问题出在请求提交格式上——ImageKit的上传接口要求用FormData格式提交,而非普通JSON对象。直接把File对象放进JSON body里会导致后端无法正确解析,进而误判fileName参数缺失。

修正步骤:

  • 创建FormData实例,将所有参数(包括file)逐个追加进去
  • 保持axios的post请求,把请求体换成FormData对象即可(axios会自动识别FormData并设置正确的multipart/form-data请求头)

修正后的代码:

const uploadFile = async (file: File) => {
  try {
    const formData = new FormData();
    // 追加文件对象
    formData.append('file', file);
    // 追加其他参数
    formData.append('publicKey', 'my_public_key');
    formData.append('signature', 'imageKit_signature');
    formData.append('expire', 'imageKit_expiry_value');
    formData.append('token', 'imageKit_token');
    formData.append('fileName', 'test123.jpg');
    formData.append('useUniqueFileName', 'false');
    formData.append('folder', userName);
    formData.append('overwriteFile', 'false');

    const response = await axios.post('https://upload.imagekit.io/api/v1/files/upload', formData);
    console.log(response.status, response.data);
  } catch (err) {
    console.error(err);
  }
};

额外注意:

  • 布尔类型的参数(比如useUniqueFileName、overwriteFile)需要转成字符串再追加到FormData中,因为FormData仅支持存储字符串或Blob/File类型
  • 如果想使用文件本身的名称作为fileName,直接替换成file.name即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:54:42