Apache FileUpload 不适用于 springboot:ServletFileUpload.parseRequest 始终为空
Posted
技术标签:
【中文标题】Apache FileUpload 不适用于 springboot:ServletFileUpload.parseRequest 始终为空【英文标题】:Apache FileUpload doesn't work with springboot : ServletFileUpload.parseRequest is always empty 【发布时间】:2022-01-21 21:50:08 【问题描述】:我正在使用 springboot 2.2.6.RELEASE 和 commons-fileupload 1.4 我已经禁用 spring.servlet.multipart 如下:
spring.servlet.multipart.enabled = false
我的控制器如下:
@RequestMapping(value = "/UploadFileServlet", method = RequestMethod.POST)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception
try
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
factory.setFileCleaningTracker(null);
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String imageFileName = request.getParameter("imageFileName");
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext())
FileItem item = (FileItem) iter.next();
if (!item.isFormField())
try (InputStream uploadedStream = item.getInputStream();
OutputStream out = new FileOutputStream(imageFileName);)
IOUtils.copy(uploadedStream, out);
catch (Exception e)
throw new RuntimeException(e);
问题:upload.parseRequest 总是返回一个空列表
【问题讨论】:
HttpServletRequest 是否未包装且 ServletInputStream 已被读取? 我不明白 HttpServletRequest.getInputStream() 如果不是包装器,则只能读取一次。见this question 我知道,而且我没有在其他任何地方读过它,我怀疑可能有一个过滤器或拦截器不是那个 Spring Boot 在其过滤器链中读取了一次 inputStream 【参考方案1】:我找到了解决方案,我有一个针对 primefaces 库的文件上传过滤器,它没有为特定的 url 模式配置,所以它正在窃取请求,在我为其配置 url 模式后,问题就解决了:
@Bean
public FilterRegistrationBean FileUploadFilter()
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new org.primefaces.webapp.filter.FileUploadFilter());
registration.setName("PrimeFaces FileUpload Filter");
registration.addUrlPatterns("/faces/*");
registration.addUrlPatterns("*.xhtml");
return registration;
【讨论】:
以上是关于Apache FileUpload 不适用于 springboot:ServletFileUpload.parseRequest 始终为空的主要内容,如果未能解决你的问题,请参考以下文章