简体   繁体   中英

Spring rest controller with @RequestBody and @RequestParam

Hi I am trying to implement a rest post method where it will take a file as parameter and json body with some other details, below is the method syntax:

@PostMapping(path = "/v1/cust-advice", produces = "application/json")
public ResponseEntity<ResponseMessage> uploadFile(@RequestBody CustomerData custData,
        @RequestParam("file") MultipartFile file) {

Can this be done in spring, if so how do I make a call to this method using postman. I tried but got the error:Current request is not a multipart request

As @M.Deinum suggests, you can't send a file as a "parameter". Files are sent as one part of a multipart body, so @RequestBody would include everything (all parts) including the file.

Instead you can declare the JSON and the file as separate "parts" with @RequestPart :

@PostMapping(value = "/upload", consumes = { "multipart/form-data" }, produces = "application/json")
public void upload(@RequestPart(name = "file", required = true) MultipartFile file,
        @RequestPart(name = "data", required = true) CustomerData data) {

Notice the consumes parameter of the @PostMapping and the name of both of the "parts".

In Postman select "form-data" under "Body". There add two entries with the same names as the @RequestPart s (in this example "file" and "data"). In the key column (a bit hidden) there is a selector where you can choose between "File" and "Text". When you choose "File", then a file selector appears in the value column. Paste the JSON into the value column of the "data" row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM