java - 使用DispatcherServlet后MultipartFile接收不到文件
高洛峰
高洛峰 2017-04-18 10:30:38
0
3
855

使用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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
Peter_Zhu

Make sure the parameter name "file" is correct?
Try this, this is how I use it, no problem.

List<String> imgUrls=new ArrayList<>();
MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
List<MultipartFile> files=multipartRequest.getFiles("file");

Plus front-end

<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<input type="submit" ">
</form>
巴扎黑
var formData = new FormData();
formData.append('file', $('#****')[0].files[0]);
迷茫

I just encountered this problem today, and I solved it after research.

This is because the configuration of the ServletRegistrationBean injected by yourself is different from the ServletRegistrationBean injected by spring boot by default. The ServletRegistrationBean you injected yourself is not configured to handle upload requests by default.

Please refer to the following configuration:

    //自动注入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;
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template