I implemented a slightly different solution based on http://rugal.ga/development/2015/10/03/uploading-file-other-than-post/ and is close to the previous post:
public class ExtendedMultipartResolver extends CommonsMultipartResolver { @Override public boolean isMultipart(HttpServletRequest request) { return (request != null && isMultipartContent(request)); } public static final boolean isMultipartContent(HttpServletRequest request) { HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod()); if (HttpMethod.POST != httpMethod && HttpMethod.PUT != httpMethod) { return false; } return FileUploadBase.isMultipartContent(new ServletRequestContext(request)); }
}
Nothing new here, except that my code relies on org.apache.commons.fileupload.FileUploadBase.isMultipartContent (RequestContext) instead of duplicating its contents.
Now, if you ever needed to do unit tests of file upload services, you could use org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload () as follows:
@Test public void testUploadFilePost() throws Exception { MockMultipartFile multipartFile = new MockMultipartFile(...); String url = ...; mockMvc.perform(fileUpload(url).file(multipartFile)).andExpect(status().isOk()); }
The above code can only issue POST requests due to the way org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder is implemented. To unit test download a PUT file, you might be interested in the following code:
private static final RequestPostProcessor PUT_REQUEST_POST_PROCESSOR = new RequestPostProcessor() { @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { request.setMethod(HttpMethod.PUT.name()); return request; } }; private static MockHttpServletRequestBuilder putFileUpload(String url, MockMultipartFile multipartFile, Object... urlVariables) { return fileUpload(url, urlVariables).file(multipartFile).with(PUT_REQUEST_POST_PROCESSOR); }
Now the test can be adapted as follows:
@Test public void testUploadFilePut() throws Exception { MockMultipartFile multipartFile = new MockMultipartFile(...); String url = ...; mockMvc.perform(putFileUpload(url, multipartFile)).andExpect(status().isOk()); }
source share