首页 > 解决方案 > Spring Boot,在 REST 控制器中上传任意数量的文件

问题描述

我想创建一个端点,它接受来自用户的任意数量的不同文件。

例如:

在此处输入图像描述

然后,我想在我的控制器中接收它作为Map<String, FilePart>(或任何其他结构,我可以从中知道哪个文件是哪个):

{
    "file1": "cactus-logo.png",
    "file2": "logo.png",
    "file3": "logo.png" (this one is actually different than file2 but has the same name)
}



我尝试了一些组合@RequestPart......

  1. 当我做:

    @RequestPart Map<String, FilePart> files
    

或者

    @RequestPart MultiValueMap<String, FilePart> files

我越来越:

org.springframework.web.server.ServerWebInputException:400 BAD_REQUEST“所需的请求部分'文件'不存在”

  1. 当我做:

    @RequestPart("files") List<FilePart> files
    

我需要提交这样的文件:

在此处输入图像描述

然后我不知道哪个文件是哪个文件(如果它们具有相同的名称):

在此处输入图像描述

  1. 最后,我可以这样做:

         @RequestPart("file1") FilePart file1,
         @RequestPart("file2") FilePart file2,
         @RequestPart("file3") FilePart file3
    

然后它按预期工作,但这样一来,就可以始终只提交 3 个文件。我想提交任意数量的文件。

  1. 正如评论中所建议的:

         @PutMapping(value = "/{component}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
         public void upload(
              @RequestParam Map<String, MultipartFile> files
         ) throws IOException {
    

并且地图总是空的:

在此处输入图像描述

在此处输入图像描述

标签: javaspringrest

解决方案


结果你应该使用@RequestParam

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestParam Map<String, MultipartFile> body) {

}

然后通过表单数据媒体发布,即:

file1: select file
file2: select file
file3: select file
....

推荐阅读