[英]Post multipart file and json in one request with @RequestPart from angular4
[英]Multipart post request from Angular To Spring
我在这里尝试将一些数据从 Angular 应用程序发布到 spring 引导后端,不幸的是,我被一个难以理解的错误困住了一天,
这是我的 API
@PostMapping("/add", consumes = ["multipart/form-data"])
fun addTeam(
@RequestPart(name = "file") file: MultipartFile,
@RequestPart(name = "body") team: Team
): ResponseEntity<*> {
val imgUrl = filesStorageService.storeFile(file)
val fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/storage/downloadFile/")
.path(imgUrl)
.toUriString()
val list = teamService.addTeam(team, fileDownloadUri)
return ResponseEntity(list, list.status)
}
这是 Angular API 调用
addTeam(team: Team, coverFile: File): Observable<boolean> {
return new Observable<boolean>(subscriber => {
let formDate = new FormData();
formDate.append('file', coverFile);
formDate.append('body', JSON.stringify(team));
this
.client
.post<ResponseWrapper<Boolean>>(environment.BASE_URL + this.ADD_TEAM, formDate, {
headers: {'Content-Type': 'multipart/form-data'},
})
......
所以在这里我有一个例外说
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
所以我发现一些解决方案告诉将 angular 内容类型设置为undefined
但这也不起作用然后我从 angular 调用中删除了内容类型
但这给了我另一个错误
2020-12-12 19:12:41.298 WARN 16892 --- [nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported]
所以我让 spring 应用程序接受application/octet-stream
但结果,
2020-12-12 19:14:39.775 WARN 16796 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundarykunWjFPmOyVdc8vn' not supported]
那么任何人都可以帮助我解决这个问题吗?
另外,我使用 postman 尝试了这个 API 并且当我将内容类型放入multipart/form-data
时它正在工作
也许你可以在你的 angular 应用程序中试试这个:
formDate.append('file', coverFile);
formDate.append('body', new Blob([JSON.stringfy(team)], { type: 'text/plain' }));
现在,在您的 Spring 中,将team
的类型更改为string
:
@PostMapping("/add", consumes = ["multipart/form-data"])
fun addTeam(
@RequestPart(name = "file") file: MultipartFile,
@RequestPart(name = "body") team: String
): ResponseEntity<*> {
现在,在获得body
的result
后,您可以使用 spring 将其解析为 object。
我最近遇到了这个问题,但是在后端使用 NestJS 并将文件名作为第三个参数添加到append()
function 有帮助。
formDate.append('file', coverFile, '<FILE_NAME_HERE>');
另外我认为你不需要明确指定'Content-Type' header,Angular 会自动检测并设置它。
在尝试了许多解决方案之后,我终于发现,如果我想在 angular 中发布许多部分,我应该将 json 值的主体包含为 json blob 的类型及其请求本身的类型,并且不需要
像这样,
formData.append('body', new Blob([JSON.stringify(team)], {
type: 'application/json'
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.