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

如何从Angular向NestJS发送FormData并获取参数(不使用FileInterceptor)

问题根因

你遇到的空Body问题由前后两端的配置错误共同导致:

  1. 前端发送FormData时错误设置了Content-Type: application/json,且Angular的HttpHeaders用法有误
  2. 后端默认的JSON解析器无法解析multipart/form-data格式的FormData请求

步骤1:修复Angular前端代码

发送FormData时不要手动设置Content-Type,浏览器会自动生成带boundary分隔符的正确请求头,手动设置会导致解析失败。另外Angular的HttpHeaders是不可变对象,调用set后需要接收返回的新实例才会生效。
修正后的代码:

let formData = new FormData();
formData.append('studentFile', file);
formData.append('studentName', name);

// 仅保留Accept头即可,不需要设置Content-Type
const headers = new HttpHeaders().set("Accept", "application/json");

this.httpClient.post("http://localhost:3000", formData, { headers }).subscribe(response => { })

步骤2:修改NestJS后端代码

你对FileInterceptor的使用有误解:它本身不会强制把文件存储到本地磁盘,只需要配置multer的内存存储,文件会以Buffer形式存在内存中,不会写入当前项目目录,你可以直接把Buffer传给ftp包上传到其他服务器。
先安装依赖类型包:

npm i -D @types/multer

修正后的接口代码:

import { Post, UseInterceptors, UploadedFile, Body } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';

@Post()
@UseInterceptors(FileInterceptor('studentFile', {
  storage: memoryStorage() // 配置内存存储,不会生成本地文件
}))
create(
  @UploadedFile() studentFile: Express.Multer.File, 
  @Body() body: { studentName: string }
) {
  // studentFile.buffer 就是文件的二进制内容,可直接传给ftp的上传方法
  console.log(studentFile.buffer);
  // 直接获取文本参数
  console.log(body.studentName);
  return "Response";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 20:06:03