Trying to write a simple file upload handler using Spring MVC 6.0.6. A file is uploaded using POST
, with encoding multipart/form-data
. On the server side, the handler is
import jakarta.servlet.annotation.MultipartConfig;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;@Controller@MultipartConfigpublic class SimpleUpload { @PostMapping(path = "/upload") public ResponseEntity<String> uploadFile(@RequestParam("File") MultipartFile file) { return file.isEmpty() ? new ResponseEntity<String>(HttpStatus.NOT_FOUND) : new ResponseEntity<String>(HttpStatus.OK); }}
Getting this error: Unable to process parts as no multi-part configuration has been provided
.
I have read other answers about this error, so I have added the multi-part configuration as follows:
@EnableWebMvc@Configuration@Import({ApplicationConfig.class})public class MvcConfig implements WebMvcConfigurer { @Bean(name = "multipartResolver") public MultipartResolver getMultipartResolver() { return new StandardServletMultipartResolver(); } @Bean(name = "filterMultipartResolver") // alternate name suggested by some people public MultipartResolver getFilterMultipartResolver() { return new StandardServletMultipartResolver(); }}
It does not seem to work, because the error is always the same.
The unit test in the application is successful:
@WebAppConfiguration@ContextConfiguration(classes = { MvcConfig.class, SimpleUpload.class })@RunWith(SpringJUnit4ClassRunner.class)public class MultipartPostRequestControllerUnitTest { @Autowired private WebApplicationContext webApplicationContext; @Test public void whenFileUploaded_thenVerifyStatus() throws Exception { MockMultipartFile file = new MockMultipartFile("File","hello.txt", MediaType.TEXT_PLAIN_VALUE,"Hello, World!".getBytes()); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .build(); mockMvc.perform(multipart("/upload") .file(file)) .andExpect(status().isOk()); }}
But sending a file via Postman to http://127.0.0.1:8080/upload returns an HTTP status 500, with root cause Unable to process parts as no multi-part configuration has been provided
.
How can I fix this?
Using Tomcat 10.1.7 to run the app.