struts2 文件下载 异常的解决方案

来源:互联网 发布:最大公倍数java编程 编辑:程序博客网 时间:2024/05/21 09:22

Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack.

如果出现以上异常 通常有两种情况

 

一种是你在action中的获取文件流的方法和后面配置的不匹配,

public InputStream getDownloadFile() {},

(get后面的第一个字母小写是否和struts里面的配置参数一致)

<param name="inputName">downloadFile</param>

 

这种情况好排查

 

第二种是中文乱码引起的

 

前台发送过来的请求中,下载文件名是中文,在后台获取的时候得到的是乱码,所有在获取输入流的时候找不到文件,

getDownloadFile()返回的是null,它照样提示你

Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack.

解决办法是获取请求参数中的文件名 并将其解码

public void setFileName(String fileName) {
         String fname = ServletActionContext.getRequest().getParameter("fileName");
                 try {
                   /*
                      * 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。
                      * 这里使用 request.setCharacterEncoding解码无效.
                      * 只有解码了 getDownloadFile()方法才能在下载目录下正确找到请求的文件
                      * */
                    fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
                 this.fileName = fname;
    }

 

可以正常下载了

原创粉丝点击