现在的位置: 首页 > 综合 > 正文

通过Struts2文件下载时Can not find a java.io.InputStream with the name 异常

2013年10月03日 ⁄ 综合 ⁄ 共 2481字 ⁄ 字号 评论关闭

异常堆栈信息:

引用:

严重: Can not find a java.io.InputStream with the name [photoStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action.
2008-4-17 17:04:44 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet default threw exception
java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [photoStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action.
        at org.apache.struts2" onclick="tagshow(event)" class="t_tag">struts2.dispatcher.StreamResult.doExecute(StreamResult.java:189)
        at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:178)
        at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:348)
        at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:253)
        at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
        at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
        at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
        at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
        at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)

可以初步判断为流不存在造成的。

检查Action的相关代码:download.java

复制内容到剪贴板

代码:

        public InputStream getPhotoStream() throws Exception {

                ServletContext sc = ServletActionContext.getServletContext();
                String realpath = sc.getRealPath("/WEB-INF/upload");
                String path = realpath + "//" + fileName;
                System.out.println("<<<" + this.fileName);
                System.out.println(">>>" + path);
                return ServletActionContext.getServletContext().getResourceAsStream(path);
        }

首先,sc变量是个没充分使用的变量,最后一行又重新去了一次:“ServletActionContext.getServletContext()”。

第二,对ServletContext的getResourceAsStream方法理解有误,该方法不是从本地路径取文件,而是从web application的路径取文件流。

而且在return行前调用ServletActionContext.getServletContext().getResourceAsStream(path)应该可以发现是空指针,比如这样:

复制内容到剪贴板

代码:

                System.out.println(">>>"
                                + ServletActionContext.getServletContext().getResourceAsStream(
                                                path));
                return ServletActionContext.getServletContext().getResourceAsStream(
                                path);

打印值应该为null,这样就可以定位错误到行了。

我对这部分代码的修改:

复制内容到剪贴板

代码:

                return ServletActionContext.getServletContext().getResourceAsStream(
                                "/WEB-INF/upload/" + this.fileName);

【上篇】
【下篇】

抱歉!评论已关闭.