[英]Conversion between org.springframework.web.multipart.MultipartFile and org.springframework.core.io.Resource
I am trying to pass a resource as a @RequestPart to my controller.我正在尝试将资源作为 @RequestPart 传递给我的控制器。
@RequestPart(name = "resource", required = false) Resource multipartFile,
It seem to work good in my integration tests where I pass it as a Resource:在我将它作为资源传递的集成测试中,它似乎运行良好:
ByteArrayResource resource = new ByteArrayResource(new byte[] {65, 66, 67});
MultipartBodyBuilder b = new MultipartBodyBuilder();
b.part("resource", resource, MediaType.APPLICATION_PDF);
return webClient.post().uri(getUri()
.contentType(MediaType.MULTIPART_FORM_DATA)
.syncBody(b.build())
.retrieve()
.bodyToMono(Long.class);
However in unit tests, I always receive resource = null.但是在单元测试中,我总是收到资源 = null。 I use MockMVC for that:我为此使用 MockMVC:
MvcResult result = mvc.perform(
multipart(getUri())
.file("resource", new byte[] {65, 66, 67})
.content(new byte[] {65, 66, 67})
.accept(MediaType.MULTIPART_FORM_DATA)
.andExpect(status().isOk())
.andReturn();
On the other hand, if I switch to using MultipartFile as parameter type in my Controller:另一方面,如果我切换到在我的控制器中使用 MultipartFile 作为参数类型:
@RequestPart(name = "resource", required = false) MultipartFile multipartFile
It works if I pass a MockMultipartFile
in unit tests, but I don't know how to pass a MultipartFile
in my integration tests (and in the other service that uses my api).如果我在单元测试中传递MockMultipartFile
,它会起作用,但我不知道如何在我的集成测试(以及使用我的 api 的其他服务中)传递MultipartFile
。 I tried implementing org.springframework.web.multipart.MultipartFile
by wrapping over my ByteArrayResource
, but it doesn't look right (and doesn't work).我尝试通过包装我的ByteArrayResource
实现org.springframework.web.multipart.MultipartFile
,但它看起来不对(并且不起作用)。 I've spent way too much time on this already... Any recommendations?我已经在这上面花费了太多时间......有什么建议吗?
PS I use StandardServletMultipartResolver PS我使用StandardServletMultipartResolver
I ended up with @RequestPart(name = "resource") Part part
in controller, which works well with both我最终得到了控制器中的@RequestPart(name = "resource") Part part
,它适用于两者
ByteArrayResource resource = new ByteArrayResource(new byte[] {1, 2, 3});
MultipartBodyBuilder b = new MultipartBodyBuilder();
b.part("resource", resource, MediaType.APPLICATION_PDF);
return webClient.post().uri(getUri()
.contentType(MediaType.MULTIPART_FORM_DATA)
.syncBody(b.build())
.retrieve()
.bodyToMono(Long.class);
and和
Part part = new MockPart("resource", new byte[]{1,2,3})
MvcResult result = mvc.perform(multipart(getUri())
.part(part)
.andExpect(status().isOk())
.andReturn();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.