Heim > Fragen und Antworten > Hauptteil
使用DispatcherServlet
@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean apiV1ServletBean(WebApplicationContext wac) {
DispatcherServlet ds = new DispatcherServlet(wac);
ServletRegistrationBean bean = new ServletRegistrationBean(ds, "/*");
bean.setName("xxx");
bean.addUrlMappings("/xxx/*");
return bean;
}
}
MultipartFile接收不到文件
@RequestMapping(method = RequestMethod.POST)
public Response<String> site(@RequestParam("file") MultipartFile file, String userId, HttpServletRequest request) {
}
错误报告:Required request part 'file' is not present
天蓬老师2017-04-18 10:32:38
确定参数名称"file"对吗?
试下这样,我是这样用的没问题。
List<String> imgUrls=new ArrayList<>();
MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
List<MultipartFile> files=multipartRequest.getFiles("file");
再加上前端的
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<input type="submit" ">
</form>
巴扎黑2017-04-18 10:32:38
var formData = new FormData();
formData.append('file', $('#****')[0].files[0]);
迷茫2017-04-18 10:32:38
我今天刚好遇到这个问题,研究解决了。
这个因为你自己注入的ServletRegistrationBean跟spring boot默认注入的ServletRegistrationBean的配置不一样。你自己注入的ServletRegistrationBean默认没有配置处理上传请求的。
请参考以下配置:
//自动注入spring boot默认的上传配置
@Autowired
private MultipartConfigElement multipartConfigElement;
@Bean
public ServletRegistrationBean apiV1ServletBean(WebApplicationContext wac) {
DispatcherServlet servlet = new DispatcherServlet(wac);
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, "/api/*");
//注入上传配置到自己注册的ServletRegistrationBean
bean.setMultipartConfig(multipartConfigElement);
bean.setName("ApiServlet");
return bean;
}