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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:00:29