简体   繁体   中英

Can't upload multipart file from postman to spring boot

I have the method:

@RequestMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.POST)
@ResponseBody
public FileResponse uploadFile(@RequestParam("file") MultipartFile file) {
    String name = storageService.store(file);

    String uri = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/download/")
            .path(name)
            .toUriString();

    return new FileResponse(name, uri, file.getContentType(), file.getSize());
}

When I try to upload file from postman I get the response:

{
    "timestamp": "2022-09-12T12:42:46.493+00:00",
    "status": 406,
    "error": "Not Acceptable",
    "path": "/upload-file"
}

Postman request: 在此处输入图像描述

Postman headers: 在此处输入图像描述

Ok, looks like the reason why this is happening is because your call in Postman is not specifying the response media type nor is your endpoint.

So your current call is saying Accept: */* (anything), and your endpoint isn't specific about what FileResponse should be returned as.

So, assuming you want a json response, you either need to update your Postman call to include

Accept: application/json

or your endpoint

 @RequestMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)

Another way to do this is to annotate your controller class with a @RestController and simplify your endpoint method by removing the @ResponseBody and going with @PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) and you should be good to go.

Example:

@RestController
public class UploadController {

    @PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public FileResponse uploadFile(@RequestParam("file") MultipartFile file) {

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