0

我编写了一个简单的页面,其中包含一个用于上传文件的表单和一个用于处理该文件的 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);
}

先感谢您 :)

4

1 回答 1

0

的请求被消耗是什么意思?请求通过拦截器堆栈到达动作,并且仍然存在。
如果由于某种原因(并且您不应该有一个,在进行简单的文件上传时),您需要在框架机制(操作、拦截器等)之外运行代码,您可以使用 Servlet。

顺便说一句,这是在 Struts2 中上传文件的正确方法,您的问题主要与

  1. 最大文件/请求上限命中;
  2. 拦截器堆栈的错误定义。

我打赌 n.1,但如果这仍然没有解决您的问题,请发布有关您的 struts.xml 的更多详细信息。

还要记住避免使用 scriptlet(正如 Boris 已经建议的那样)并且永远不要直接调用 JSP:总是通过一个 Action。

于 2016-02-04T11:15:00.410 回答