SpringBoot使用webxml后上传文件异常multipart-form is disabled
今天遇到了上传文件的一个问题,项目环境是Springboot+JSP。因为使用了公司内部的框架,所以也需要使用web.xml。
一、表单+后台处理代码
1 | <form method="post" action="<c:url value="/student/commit"/>" enctype="multipart/form-data"> |
一个非常简单的文件上传,错误里的 no multi-part configuration has been provided 是什么意思,未提供文件上传的配置?
可我分明在 spring-web.xml 里加入了相应的配置。
我再仔细看,Could not parse multipart servlet request,没有 servlet 的配置?
异常堆栈:
1 | 2019-08-20 15:56:44.084 ERROR 5104 --- [esin-port-80-48] o.s.b.w.servlet.support.ErrorPageFilter : Forwarding to error page from request [/admin/student/import.do] due to exception [Failed to parse multipart servlet request; nested exception is javax.servlet.ServletException: multipart-form is disabled; check @MultipartConfig annotation on 'geli-springboot'.] |
二、谜题之解
我这才意识到,SpringMVC 是依赖 Servlet 的,虽然 SpringMVC 能识别 Servlet,但它底层的 Servlet 也许还不能识别文件上传。
SpringMVC 官网的 refference 去看文档,果然,我发现了一些猫腻:
Once Servlet 3.0 multipart parsing has been enabled in one of the above mentioned ways you can add the StandardServletMultipartResolver to your Spring configuration
在配置 SpringMVC 的 StandardServletMultipartResolver 之前必须先配置 Servlet,官网提供的方案有:
- 1.mark the DispatcherServlet with a “multipart-config” section in web.xml(在 web.xml 文件中的 DispatcherServlet 元素里,加上一个 multipart-config)
- 2.with a javax.servlet.MultipartConfigElement in programmatic Servlet registration
- 3.in case of a custom Servlet class possibly with a javax.servlet.annotation.MultipartConfig annotation on your Servlet class
我选择了第一种方案,打开 webapp/WEB-INFO 目录下的 web.xml,往 DispatcherServlet 里加了一行
1 | <multipart-config/> |
再运行项目,就可以正常地上传文件了。
web.xml 全部内容如下:
1 | <?xml version="1.0" encoding="UTF-8"?> |
参考文档:
https://www.iloveqyc.com/2016/06/03/springmvc-upload-file-fail-servlet/
https://juejin.im/post/5a730f895188257a6d634f0a#heading-6
Spring揭秘–寻找遗失的web.xml