简体   繁体   English

无法将多部分文件从 postman 上传到 spring 启动

[英]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:当我尝试从 postman 上传文件时,我得到响应:

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

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

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

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.好的,看起来发生这种情况的原因是因为您在 Postman 中的调用没有指定响应媒体类型,也没有指定您的端点。

So your current call is saying Accept: */* (anything), and your endpoint isn't specific about what FileResponse should be returned as.因此,您当前的通话是说Accept: */* (anything),并且您的端点并未具体说明FileResponse应返回的内容。

So, assuming you want a json response, you either need to update your Postman call to include因此,假设您想要 json 响应,您需要更新您的 Postman 调用以包含

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.另一种方法是使用 @RestController 注释您的 controller @RestController并通过删除@ResponseBody并使用@PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)来简化您的端点方法和对 go 好。

Example:例子:

@RestController
public class UploadController {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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