如何在NestJS API中接收Angular提交的Multipart表单数据
解决Angular提交FormData到NestJS API的"Multipart: Boundary not found"问题
问题根源
错误出在手动设置了Content-Type: multipart/form-data请求头,导致浏览器无法自动生成用于分隔表单字段的boundary标识,后端NestJS无法正确解析multipart格式的数据。
解决方案
1. 修正Angular请求代码
移除请求头中手动设置的Content-Type,HttpClient在发送FormData时会自动生成包含boundary的正确Content-Type:
async save() { this.error = (!this.image || !this.email || !this.name); if(!this.error) { const form = new FormData(); form.append("image", this.image); form.append("email", this.email); form.append("name", this.name); try { const res = await firstValueFrom( this.httpClient.post(`${environment.api_url}/emp`, form, { headers: { 'x-api-key': environment.api_psk // 移除手动设置的Content-Type } }) ); this.empid = res.id; this.imageurl = res.url; this.page = 2; } catch (err) { throw err; } } }
2. 修正NestJS控制器代码
- 移除多余的
@UploadedFiles()装饰器(FileInterceptor仅处理单个文件,@UploadedFiles()用于多文件场景) - 添加
@Body()装饰器获取FormData中的普通字段(email、name)
import { Body } from '@nestjs/common'; @Post("emp") @UseInterceptors(FileInterceptor("image")) @HttpCode(HttpStatus.OK) async createEmpEntry( @UploadedFile() file: Express.Multer.File, @Body() body: { email: string; name: string } // 获取普通表单字段 ) { console.log('上传的文件:', file); console.log('表单字段:', body); // 后续业务逻辑实现 }
额外验证点
- 确认
this.image确实是File类型(可通过console.log(this.image)检查) - 确保NestJS项目中已正确安装
multer依赖(FileInterceptor依赖multer,NestJS初始化时通常已自动配置)
内容的提问来源于stack exchange,提问作者user176504
相关产品推荐
相关产品推荐

