search

Home  >  Q&A  >  body text

java - 使用DispatcherServlet后MultipartFile接收不到文件

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

高洛峰高洛峰2807 days ago863

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:32:38

    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>

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:32:38

    var formData = new FormData();
    formData.append('file', $('#****')[0].files[0]);

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:32:38

    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;
        }

    reply
    0
  • Cancelreply