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

Angular+PrimeNG向Spring Boot上传Multipart File遇415错误求助

Angular 13 + PrimeNG 13 上传Multipart File到Spring Boot报415错误问题

问题现象

使用Angular 13.3.8结合PrimeNG 13.2.1向Spring Boot后端上传文件时,POST请求返回状态码415,错误信息为Unsupported Media Type,Spring Boot日志显示:

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]

相关代码

PrimeNG文件上传组件(HTML)

<p-card header="Import file"> 
  <p-fileUpload
    customUpload="true"
    (uploadHandler)="onUpload($event)" 
    [multiple]="false"
    accept=".stk">
  </p-fileUpload>
</p-card>

Component.ts代码

onUpload(event): any {
  if (event.files.length === 0) {
    return;
  }
  const file = event.files[0];

  this.service.importFile(file).subscribe(
    (response) => {
      console.log(response);
    },
    (error) => {
      console.error(error);
    }
  );
}

Angular Service代码(原错误版本)

importFile(file: File): Observable<any>{
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);
  const headers = new HttpHeaders();
  headers.set('Content-Type', null);
  headers.set('Accept', "multipart/form-data");
  headers.set('encType', "multipart/form-data");
  let params = new HttpParams();
  return this.http.post(baseUrl+"/uploadFile", formData, { headers ,params});
}

Spring Boot接口代码

@PostMapping(value = "/importStackup", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<String> importStackSet(@RequestParam("file") MultipartFile multiPart) {
  // 业务代码
}

问题原因及修复方案

  1. HttpHeaders设置错误:
    HttpHeaders是不可变对象,调用set()方法不会修改原对象,需要重新赋值。同时,上传FormData时不需要手动设置Content-Type,浏览器会自动添加正确的multipart/form-data及boundary信息,手动设置反而会导致请求头错误。

  2. 请求路径不匹配:
    Angular中请求路径是baseUrl+"/uploadFile",但Spring Boot接口路径是/importStackup,两者不一致,需要统一路径。

  3. 冗余的encType设置:
    encType不是HTTP标准请求头字段,无需添加。

修正后的Angular Service代码

importFile(file: File): Observable<any>{
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);
  // 仅设置Accept头,无需手动指定Content-Type
  const headers = new HttpHeaders()
    .set('Accept', "multipart/form-data");
  let params = new HttpParams();
  // 修正请求路径与Spring Boot接口一致
  return this.http.post(baseUrl+"/importStackup", formData, { headers, params });
}

也可以完全不自定义headers,Angular HttpClient在发送FormData时会自动处理请求头:

importFile(file: File): Observable<any>{
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);
  return this.http.post(baseUrl+"/importStackup", formData);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:27:17