英文:
Spring Boot, upload any amount of files in REST controller
问题
我想创建一个端点,接受用户上传的任意数量的不同文件。
例如:
然后,我想在我的控制器中将其作为 Map<String, FilePart>
(或者从中我可以知道哪个文件是哪个的任何其他结构)来接收:
{
"file1": "cactus-logo.png",
"file2": "logo.png",
"file3": "logo.png"(这一个实际上与file2不同,但文件名相同)
}
我尝试过一些@RequestPart
的组合...
- 当我使用:
@RequestPart Map<String, FilePart> files
或者
@RequestPart MultiValueMap<String, FilePart> files
我得到:
org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Required request part 'files' is not present"
- 当我使用:
@RequestPart("files") List<FilePart> files
我需要像这样提交文件:
然后我无法知道哪个文件是哪个(如果它们具有相同的名称):
- 最后,我可以这样做:
@RequestPart("file1") FilePart file1,
@RequestPart("file2") FilePart file2,
@RequestPart("file3") FilePart file3
然后它按预期工作,但是这样只能始终提交3个文件。我想提交任意数量的文件。
- 如评论中所建议的:
@PutMapping(value = "/{component}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(
@RequestParam Map<String, MultipartFile> files
) throws IOException {
而且这个映射始终为空:
英文:
I'd like to create an endpoint which accepts any amount od different files from user.
For example:
Then, I'd like to receive it in my controller as a Map<String, FilePart>
(or any other structure from which I'll know which file is which):
{
"file1": "cactus-logo.png",
"file2": "logo.png",
"file3": "logo.png" (this one is actually different than file2 but has the same name)
}
I tried some combinations of @RequestPart
...
-
When I do:
@RequestPart Map<String, FilePart> files
or
@RequestPart MultiValueMap<String, FilePart> files
I'm getting:
> org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Required request part 'files' is not present"
-
When I do:
@RequestPart("files") List<FilePart> files
I need to submit files like that:
And then I don't have the information which file is which (if they have the same name):
-
Finally, I can do:
@RequestPart("file1") FilePart file1, @RequestPart("file2") FilePart file2, @RequestPart("file3") FilePart file3
And then it works as expected, but with that, it's possible to submit always only 3 files. I'd like to submit any number of files.
-
As suggested in comments:
@PutMapping(value = "/{component}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public void upload( @RequestParam Map<String, MultipartFile> files ) throws IOException {
and the map is always empty:
答案1
得分: 2
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestParam Map<String, MultipartFile> body) {
}
然后通过表单数据媒体进行发布:
file1: 选择文件
file2: 选择文件
file3: 选择文件
....
英文:
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestParam Map<String, MultipartFile> body) {
}
Then post via form-data media ie:
file1: select file
file2: select file
file3: select file
....
答案2
得分: 0
我没有提到我在使用响应式的 WebFlux,因此 @Toàn Nguyễn Hải 提供的解决方案在我的情况下不适用。我相信它适用于非响应式的应用程序。
对于 WebFlux,以下方法有效:
公平地说,我不会接受任何答案,因为它们都可以。谢谢!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论