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

Angular向Spring发PUT请求报错:Required request part 'file' is not present

解决Angular PUT请求中Spring无法识别FormData里的'file'字段问题

看起来你遇到的问题核心在于Angular端传递给FormData的exam.file并不是一个真正的File对象——从你的请求负载里file对应的4.868,68就能看出来,这是一个普通字符串,而Spring后端的@RequestParam("file") MultipartFile只能识别文件类型的请求部分,自然就会抛出"Required request part 'file' is not present"的错误。Postman能正常工作,是因为你在Postman里正确选择了本地文件作为file参数,和Angular端的传递逻辑完全不同。

解决方案步骤

1. 修正Examen类型定义,确保file为File类型

先检查你的Examen接口/类,把file字段明确声明为File类型,避免传入非文件值:

export interface Examen {
  naam: string;
  file?: File; // 这里指定为File类型
  // 其他字段...
}

2. 从文件选择器正确获取File对象

在组件模板里使用文件输入控件,并在用户选择文件时,把真实的File对象赋值给exam.file:

<!-- 组件模板 -->
<input type="file" (change)="onFileSelected($event)">

对应的组件逻辑:

// 组件类代码
onFileSelected(event: Event): void {
  const inputElement = event.target as HTMLInputElement;
  if (inputElement.files && inputElement.files.length > 0) {
    this.exam.file = inputElement.files[0]; // 将选中的文件对象赋值给exam.file
  }
}

3. 验证FormData中的file类型

在你的ExamService里添加日志,确认exam.file是真正的File对象:

updateExamById(id, exam: Examen) {
  const fd = new FormData();
  // 验证file类型
  console.log('exam.file是否为File对象:', exam.file instanceof File); // 应该返回true
  fd.append('name', exam.naam);
  if (exam.file) {
    fd.append('file', exam.file);
  }
  return this.http.put<Examen>(APIURL + '/update/' + id, fd);
}

4. 不要手动设置Content-Type

Angular的HttpClient在发送FormData时,会自动生成包含boundary的multipart/form-data请求头,手动设置反而会因为缺少boundary导致Spring无法解析请求,所以保持默认即可。

额外验证

调整完成后,打开浏览器开发者工具的Network面板,找到这个PUT请求,查看Payload部分:file字段应该显示为(binary),而不是普通文本,这就说明文件已经正确传递了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:49:06