Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send JSON and Image with single request. Angular + Spring Boot

Spring Rest Controller

@PostMapping(
    value = "/post",
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}
)
public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file) {
    // do something with User and file
    return ResponseEntity.ok().build();
}

Angular Service

@Injectable()
export class UploadFileService {

  constructor(private http: HttpClient) { }
  pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
    let formdata: FormData = new FormData();
    formdata.append('file', file);
    formdata.append('user', JSON.stringify(new User('John', 12)))

    const req = new HttpRequest('POST', '/post', formdata, {
      reportProgress: true,
    });

    return this.http.request(req);
  }
}

When I try to send the request I get 500 Internal Server Error.

Here's a request header

POST /post HTTP/1.1
Host: localhost:4200
Connection: keep-alive
Content-Length: 152881
Accept: application/json, text/plain, */*
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarydaQb5yaWw2xu1V9r
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Request payload

------WebKitFormBoundarydaQb5yaWw2xu1V9r
Content-Disposition: form-data; name="file"; filename="Screen Shot 2017-10-24 at 8.49.13 PM.png"
Content-Type: image/png


------WebKitFormBoundarydaQb5yaWw2xu1V9r
Content-Disposition: form-data; name="user"

{"name":"John","age":12}
------WebKitFormBoundarydaQb5yaWw2xu1V9r--

Note: If in Spring rest controller I change parameter type User to String it works.

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

like image 479
A0__oN Avatar asked Dec 11 '17 15:12

A0__oN


1 Answers

Changing

public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file)

to

public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file)

and changing the request to something like this will work:

curl -i -X POST -H "Content-Type: multipart/form-data" \
-F 'user={"name":"John","age":12};type=application/json' \
-F "[email protected]" http://localhost:8080/post

For consumes only MediaType.MULTIPART_FORM_DATA_VALUE is required.

To make above kind of request in angular, something like this can be done:

const userBlob = new Blob(JSON.stringify(new User('John', 12)),{ type: "application/json"});
formdata.append('user', userBlob);
like image 154
Saheb Avatar answered Nov 16 '22 19:11

Saheb