Expose multipart data in ServerRequest
See original GitHub issueWe are currently developing a Spring MVC environment using functional routing like this:
router {
POST("/user-photo/", userImageHandler::create)
}
@Component("user.Image")
class UserImageHandler : PassHandler() {
fun create(serverRequest: ServerRequest) = success {
val multipartRequest = (serverRequest.servletRequest() as? MultipartHttpServletRequest) ?:
throw ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE,
"Request is not a multipart request"
)
val file: MultipartFile = multipartRequest.getFile("file") ?: throw ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE,
"Missing file with name: file"
)
....
}
}
The ServerRequest is the https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/function/ServerRequest.html interface. The only way to access files seem to be the casting method we do right now - serverRequest.servletRequest().parts
is empty.
This is the integration test:
val file = MockMultipartFile(
"blank.jpg",
"blank.jpg",
"image/jpg",
getImageBytes()
)
mockMvc.perform(
MockMvcRequestBuilders.multipart("/user-photo/")
.file(file)
.accept(MediaType.APPLICATION_JSON)
).andExpect(
MockMvcResultMatchers.status().isOk
)
In the integration test the serverRequest.servletRequest part is of type SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@71f08480]
and thus not a decendant of MultipartHttpServletRequest
.
Is there a smarter way to access multipart files with the ServerRequest interface? Otherwise I would think that HttpServletRequest
is missing a getFiles()
method.
I found an way to access multipart files but it’s a few levels deep and would require a lot of casting:
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top GitHub Comments
As it turned out, the solution was to use
part
(andMockPart
) on the builder, instead offile
.MultipartFile
is a Spring abstraction introduced before Servlet offeredPart
. As such, theHttpServletRequest
does not “know” aboutMultipartFile
objects, onlyPart
.This test works for me:
Though your initial problem is fixed, I am going to keep this issue around as a feature request to expose multipart data on WebMvn.fn’s
ServerRequest
directly, without resorting toHttpServletRequest
.I tested it with a real API request as well and it works. But what I’m really trying to achieve here is to get the integration test to run with MockMvc. I posted the integration test content in the initial post.
I created a fairly minimal repo here: https://github.com/jonasbark/spring-framework-24909