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

如何通过expo-image-picker上传图片至NestJS(Multer)服务?

Expo ImagePicker 上传图片到 NestJS Multer 接口问题解决

问题核心

你的后端通过 FileInterceptor('file') 无法解析上传的文件(file 显示 undefined),但请求体中能看到 file 的原始数据,且 Postman 测试接口正常,说明问题出在前端 FormData 的构造或请求发送方式上。

解决方案

1. 正确构造 FormData(关键修正)

React Native/Expo 中的 FormData 对文件对象的格式有严格要求,必须匹配以下规则:

  • 使用 ImagePicker 返回的原始 mimeType,不要硬写类型
  • 处理 iOS 端的 file:// 前缀
  • 给文件对象添加合法的文件名
import { Platform } from 'react-native';

// 从 ImagePicker 获取的图片资源
const imageAsset = result.assets[0];
const formData = new FormData();

// 核心:用图片原生的 mimeType,自动匹配格式
formData.append('file', {
  uri: Platform.OS === 'ios' ? imageAsset.uri.replace('file://', '') : imageAsset.uri,
  name: `upload-${Date.now()}.${imageAsset.mimeType.split('/')[1]}`, // 生成唯一文件名
  type: imageAsset.mimeType, // 直接复用 ImagePicker 返回的类型
});

// 追加其他表单字段
formData.append('description', timelineEvent.description);
formData.append('eventType', timelineEvent.eventType);

2. 正确发送请求(禁止手动设置 Content-Type)

绝对不要手动设置 Content-Type: multipart/form-data,因为 FormData 会自动生成包含 boundary 的请求头,手动设置会丢失这个关键参数,导致 Multer 无法解析文件。

Fetch 示例:

const response = await fetch('你的接口地址', {
  method: 'POST',
  headers: {
    'x-token': '你的授权token',
    // 这里不要加 Content-Type!
  },
  body: formData,
});

Axios 示例:

import axios from 'axios';

const response = await axios.post('你的接口地址', formData, {
  headers: {
    'x-token': '你的授权token',
    // 同样不要手动设置 Content-Type
  },
});

3. 后端快速排查(确认配置)

虽然 Postman 测试正常,但可以快速验证:

  • 确保 FileInterceptor('file') 的字段名 file 和前端 FormData 中的 key 完全一致
  • 检查 Multer 的存储配置(如 dest 目录)是否有读写权限

为什么之前的方式失败?

  • Blob 方式:Expo 中的 Blob 实现和 Web 存在差异,Multer 无法正确解析这种格式的文件
  • Buffer 方式:React Native 环境默认没有 Node.js 的 Buffer 对象,且该方式不符合 multipart/form-data 的标准格式
  • 第二种方式的问题:硬写 type: 'image/jpg' 可能和图片实际类型不匹配(比如 PNG 图片),或手动设置了 Content-Type 导致丢失 boundary

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:57:42