Здравствуйте.
Необходимо реализовать rest сервис загрузки фалов на сервер.
Вот код метода контроллера:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile multipartFile) {
if (multipartFile == null)
return new ResponseEntity<String>("Error", HttpStatus.NOT_FOUND);
try {
int read = 0;
File newFile = new File("/" + multipartFile.getName());
FileOutputStream fos = new FileOutputStream(newFile);
CountingOutputStream out = new CountingOutputStream(fos);
byte[] bytes = new byte[1024];
while ((read = multipartFile.getInputStream().read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity("" + "/" + multipartFile.getName(), HttpStatus.OK);
}
В файле конфигурации объявил:
@Configuration
@EnableWebMvc
@ComponentScan("com.kidsdays.server")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setSupportedMediaTypes(Arrays.asList(new MediaType[] {MediaType.APPLICATION_JSON, MediaType.MULTIPART_FORM_DATA}));
converters.add(converter);
}
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return new CommonsMultipartResolver();
}
Приложение запускается без ошибок, но в результате вызова ошибка
HTTP Status 500 - Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)