Upload a JSON Object (User information) and Multip

2019-05-29 07:58发布

问题:

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

}

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.

Spring rest :user Object

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

Question: How to send request from Angular so that on Spring I can get User Object instead of String.

回答1:

public ResponseEntity<PersonDTO> createPerson(@RequestParam("user") User personDTO, @RequestParam("file") MultipartFile[] file){

needs to be changed to

public ResponseEntity<PersonDTO> createPerson(@RequestPart("file") MultipartFile[] file, @RequestPart("user") User personDTO){

to let spring boot know that these parameters would be coming as separate parts.