Upload a JSON Object (User information) and Multiple Image with single request. Angular + Spring Boot

守給你的承諾、 提交于 2020-01-23 17:09:13

问题


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.



来源:https://stackoverflow.com/questions/50462894/upload-a-json-object-user-information-and-multiple-image-with-single-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!