我编写了一个简单的页面,其中包含一个用于上传文件的表单和一个用于处理该文件的 jsp。
我的问题是,当文件上传时,请求对象由 Struts 拦截器处理,当涉及到 jsp 页面时,它已经被“消耗”了,因此使用诸如“ServletFileUpload.parseRequest() 之类的方法读取请求的调用" 返回空列表。
我已经找到了一个可行的解决方案,但这需要重新启动Tomcat,并且由于必须在生产服务器上添加页面,如果有办法不重新启动它会更好。
现在,我尝试和工作的是:
1)在struts.xml中我添加了
<include file="custom/struts-custom.xml"/>
2) 在 struts-custom.xml 中我写道:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.action.excludePattern" value="/path_to_my_jsp/page.jsp"/>
</struts>
有了这个我可以绕过struts拦截器上传文件。
有更好/更清洁的解决方案吗?正如我所说,最好的解决方案是不需要重新启动应用程序服务器。
即使我不认为问题与代码有关,我也会发布它。
page.html:
<form action="upload.jsp" method="post" enctype="multipart/form-data" TARGET="Report_Down"
onSubmit="if(document.getElementById('file1').value == '') return false;">
Input File <input type="file" name="file1" id="file1">
<input type="submit" value="Upload">
</form>
上传.jsp:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 2);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
try {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
item.write(uploadedFile);
//do something...
}
catch(Exception e) {
//...
}
}
}
getServletContext().getRequestDispatcher(forwardUrl).forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
先感谢您 :)