org.springframework.web.multipart.MultipartFile和org.springframework.core.io.Resource之间的转换

问题描述 投票:1回答:1

我正在尝试将资源作为@RequestPart传递给我的控制器。

@RequestPart(name = "resource", required = false) Resource multipartFile,

在我将其作为资源传递的集成测试中,它似乎工作良好:

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);

但是在单元测试中,我总是收到resource = null。我为此使用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();

另一方面,如果我在控制器中切换为使用MultipartFile作为参数类型:

@RequestPart(name = "resource", required = false) MultipartFile multipartFile

[如果我在单元测试中通过MockMultipartFile,则可以使用,但是我不知道如何在集成测试中(以及在使用我的api的其他服务中)通过MultipartFile。我尝试通过包裹org.springframework.web.multipart.MultipartFile来实现ByteArrayResource,但是它看起来不正确(并且不起作用)。我已经在此上花了太多时间...有什么建议吗?

P.S。我使用StandardServletMultipartResolver

java spring rest spring-mvc multipart
1个回答
0
投票

我最终在控制器中以@RequestPart(name = "resource") Part part结束了,这两个都很好用

© www.soinside.com 2019 - 2024. All rights reserved.