使用单个请求上载JSON对象(用户信息)和多个图像。 Angular + Spring Boot

时间:2018-05-22 08:15:27

标签: angular spring-boot multipartform-data angular2-services

Spring Rest Controller

 @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);
    }

Angular Service

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 controller读取。

Spring rest:user Object

 {"avatar":"","username":"","gender":"male","country":[],"about":"sdf"}

问题:如何从Angular发送请求,以便在Spring上我可以获取User Object而不是String。

1 个答案:

答案 0 :(得分:1)

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知道这些参数将作为单独的部分出现。