使用单个请求上传 JSON 对象(用户信息)和多个图像.角 + 弹簧靴 [英] Upload a JSON Object (User information) and Multiple Image with single request. Angular + Spring Boot
本文介绍了使用单个请求上传 JSON 对象(用户信息)和多个图像.角 + 弹簧靴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
弹簧座控制器
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<PersonDTO> createPerson(@RequestParam("user") User personDTO, @RequestParam("file") MultipartFile[] file){
return new ResponseEntity<>(null, responseHeaders, HttpStatus.OK);
}
角度服务
createPerson(personClass : User, files : File[]): Observable<HttpEvent<{}>>{
let formdata: FormData = new FormData();
//Get Cities
var obj = JSON.parse(JSON.stringify(personClass.city));
var myObj = {avatar:personClass.avatar,username:personClass.username , gender:personClass.gender, country:personClass.country, city:obj.code, about:personClass.about};
//get upload images
let fileCount: number = files.length;
if (fileCount > 0) { // a file was selected
for (let i = 0; i < fileCount; i++) {
formdata.append('file', files[i]);
}
}
const userBlob = new Blob([myObj],{ type: "application/json"});
// User object to FormData
formdata.append('user',JSON.stringify(myObj));
return this.http.post(`${this.webServiceEndpoint}/person`,formdata)
.map(res => res.json() )
.catch(this.handleError);
}
请注意:如果在 Spring rest 控制器中我将参数类型 User 更改为 String 它可以工作并且多个文件能够从 Spring rest 控制器读取.
Please Note: If in Spring rest controller I change parameter type User to String it works and multiple files are able to read from Spring rest controller.
弹簧休息:用户对象
{"avatar":"","username":"","gender":"male","country":[],"about":"sdf"}
问题:如何从 Angular 发送请求,以便在 Spring 上我可以获得用户对象而不是字符串.
Question: How to send request from Angular so that on Spring I can get User Object instead of String.
推荐答案
public ResponseEntity<PersonDTO> createPerson(@RequestParam("user") User personDTO, @RequestParam("file") MultipartFile[] file){
需要改成
public ResponseEntity<PersonDTO> createPerson(@RequestPart("file") MultipartFile[] file, @RequestPart("user") User personDTO){
让 spring boot 知道这些参数将作为单独的部分出现.
to let spring boot know that these parameters would be coming as separate parts.
这篇关于使用单个请求上传 JSON 对象(用户信息)和多个图像.角 + 弹簧靴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文