struts的文件下载
一、jsp
<body> <table border="1" align="center"> <tr> <td>编号</td> <td>文件名</td> <td>操作</td> </tr> <c:forEach var="fileName" items="${fileNames}" varStatus="vs"> <tr> <td>${vs.count}</td> <td>${fileName}</td> <td> <!-- 构建一个url --> <c:url var="url" value="down_down"> <c:param name="fileName" value="${fileName}"></c:param> </c:url> <a href="${url}">下载</a> </td> </tr> </c:forEach> </table> </body>
二、DownAction.java
/****************第二步:文件下载**********************/ //1、获取下载的名字 private String fileName; private void SetFileName(String fileName) { //传入中文,处理乱码问题 try { fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } this.fileName=fileName; } //2.下载提交的业务方法(在struts.xml中配置返回stream) public String down() { return "download"; } //3.返回流的方法 public InputStream getAttrInputStream(){ return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName); } //4.下载显示的文件名 public String getDownFileName() { //告诉浏览器编码格式 try { fileName = URLEncoder.encode(fileName,"UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return fileName; }
三、
<action name="down_*" class="cn.itcast.e_fileupload.DownAction" method="{1}"> <result name="list">/e/list.jsp</result> <!-- 下载操作 --> <result name="download" type="stream"> <!-- 运行下载的文件类型:指定为所有的二进制文件类型 --> <param name="contentType">application/octet-stream</param> <!-- 对应的Action中的属性:返回流的属性【其实就是getAttrInputStream()】 --> <param name="inputName">attrInputStream</param> <!-- 下载头:包括浏览器显示的文件名 --> <param name="contentDisposition">attachment;filename=${downFileName}</param> <!-- 缓冲区设置 --> <param name="bufferSize">1024</param> </result> </action>