如何使用Sring Boot阅读多部分内容?

时间:2019-04-28 19:47:13

标签: java spring multipartform-data

我的控制器中包含以下内容:

@PostMapping(value = "{storageId}/{repositoryId}", consumes = "multipart/form-data")
public ResponseEntity uploadViaPost(@PathVariable(name = "storageId") String storageId,
                                    @PathVariable(name = "repositoryId") String repositoryId,
                                    @RequestPart("content")
                                    MultipartFile multipartFile,
                                    HttpServletRequest request)
            throws IOException
{
...
}

如果我想获取其余的多部分字段(不是文件),我需要使用哪些类/注释?有人可以提供一个如何处理其余字段的示例,例如:

----------------GHSKFJDLGDS7543FJKLFHRE75642756743254
Content-Disposition: form-data; name="platform"

UNKNOWN
----------------GHSKFJDLGDS7543FJKLFHRE75642756743254
Content-Disposition: form-data; name="version"

1.0
----------------GHSKFJDLGDS7543FJKLFHRE75642756743254
Content-Disposition: form-data; name="description"

UNKNOWN

1 个答案:

答案 0 :(得分:1)

您可以在方法签名中使用多个@RequestPart注释,并使用required=false标志注释所需的数据。

例如:

@PostMapping(path = "/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity testEndpoint(@RequestPart("file") MultipartFile file,
                                   @RequestPart("version") String version,
                                   @RequestPart(name = "platform", required = false) String platform) {
    log.info("file_name = {}, version = {}, platform = {}", file.getOriginalFilename(), version, platform);
    return ResponseEntity.ok().build();    
}

并出于测试目的卷曲:

curl -X POST \
  http://localhost:8080/test \
  -H 'Content-Type: multipart/form-data' \
  -F file=@/path/to/file/test.txt \
  -F version=1.0.0 \
  -F platform=Test-Platform