Struts 从项目中下载文件

来源:互联网 发布:jquery 获取数组元素 编辑:程序博客网 时间:2024/06/03 07:17

效果图:

这边下载,是把项目中存在的文件,下载下来。

Java:

private String fileName;            public String getFileName() {          return fileName;    }        public void setFileName(String fileName) {          this.fileName = fileName;    }      public InputStream  getDownloadFile() throws Exception  {        this.fileName = "EC平台设备列表.xlsx";        this.fileName = new String(this.fileName.getBytes("GBK"),"ISO-8859-1");         return ServletActionContext.getServletContext().getResourceAsStream("download/EC平台设备列表.xlsx") ;  //这边是项目中要下载的文件路径    }    public String execute() throws Exception {          return SUCCESS;      } 
Struts.xml:

<action name="getDownloadFile" class="equipmentInfoAction"><result name="SUCCESS" type="stream"><param name="contentType">application/vnd.ms-excel;</param><param name="cacheControl">no-cache</param><param name="inputName">downloadFile</param>//downloadFile对应InputStream  getDownloadFile();<param name="contentDisposition">attachment;filename="${fileName}"</param><param name="bufferSize">4096</param></result></action>
如果,出现Java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.lang.String 这个错误,把action中的method属性删除。

jsp:

 <button id="button_exp" class="btn btn-sm btn-inverse">模板下载</button>

js:

$("#button_exp").click(function(event) {/* Act on the event */window.location.href = "getDownloadFile.action";});
至此,Struts的下载就搞定了!可以试试咯~

1 0