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

如何在Angular与Spring Boot中同POST请求上传DTO与文件?

问题分析与解决方案

核心问题

报错Content-Type 'application/octet-stream' is not supported的原因在于:

  1. Angular默认给FormData中的JSON字符串字段设置的Content-Type是text/plain,而Spring的@RequestPart("data")期望接收application/json类型的数据,无法自动解析字符串为VideoDto对象。
  2. Spring控制器中混用@RequestPart和@RequestParam处理multipart请求,导致解析逻辑冲突。

修正步骤

1. 修改Angular请求代码

将JSON字符串转为Blob并指定Content-Type为application/json,确保Spring能正确识别并解析DTO:

submit() {
  const formData = new FormData();

  const videoDto = {
    name: this.form.get('name')?.value,
    code: null,
    storageName: null,
    category: "vacances"
  };

  // 将JSON转为Blob并设置正确的Content-Type
  const dataBlob = new Blob([JSON.stringify(videoDto)], { type: 'application/json' });
  formData.append('data', dataBlob);
  
  // 文件直接添加,Angular会自动处理其Content-Type
  const file = this.form.get('file')?.value;
  if (file) {
    formData.append('file', file);
  }
  
  this.http.post('http://localhost:8095/uploadfile/data', formData).subscribe(
    (response) => console.log(response),
    (error) => console.error(error.message)
  );
}

2. 修改Spring控制器代码

统一使用@RequestPart接收multipart请求的所有部分(JSON和文件),避免解析逻辑冲突,同时明确指定请求类型:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;

@PostMapping(value="/uploadfile/data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<FileUploadResponse> createVideo(
    @RequestPart("data") VideoDto data, 
    @RequestPart("file") MultipartFile multipartFile) 
    throws IOException, ImageAllreadyOwenedException 
{   
    FileUploadResponse response = fileSystemStorage.storeFile(multipartFile);
    // 可在此添加VideoDto的业务处理逻辑(如存入数据库)
    return new ResponseEntity<>(response, HttpStatus.OK);
}

关键说明

  • Postman能正常运行是因为手动给JSON部分设置了application/json的Content-Type,而Angular默认不会自动添加。
  • Spring Boot默认已配置MultipartResolver,无需额外配置即可处理文件上传。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:02:49