Struts2文件下载 1 public class DownLoadAction extends ActionSupport{ 2 3 private static final long serialVersionUID = 1L; 4 //要下载的文件名 5 private String filename; 6 public String getFilename() { 7 return filename; 8 } 9 public void setFilename(String filename) { 10 this.filename = filename; 11 } 12 13 /** 14 * 这个方法的方法名称是由result的type的属性值对应的类的属性决定的 15 * (inputName) 16 * @throws FileNotFoundException 17 */ 18 public InputStream getInputStream() throws FileNotFoundException { 19 String path = ServletActionContext.getRequest().getRealPath("/download/"); 20 return new FileInputStream(new File(path, filename)); 21 } 22 23 /** 24 * struts2里面的下载 25 * 我们实际被访问的页面只是做了一个页面跳转 26 */ 27 public String stream() { 28 return SUCCESS; 29 } 30 }
struts.xml
1 <!DOCTYPE struts PUBLIC 2 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 3 "http://struts.apache.org/dtds/struts-2.3.dtd"> 4 <struts> 5 <!-- 配置常量--> 6 <!-- 配置struts2编码常量只针对post提交方式 7 get提交方式的乱码问题需要我们手动解决 8 --> 9 <constant name="struts.i18n.encoding" value="UTF-8"/> 10 <!-- 配置访问action的后缀名 --> 11 <constant name="struts.action.extension" value="action,,"/> 12 <!-- 13 struts.devMode:struts2的开发者模式 14 在开发阶段:我们一般都会设置为true,这样我们在修改struts.xml的时候,就不用重启服务器了 15 生产环境,设置为false 16 --> 17 <constant name="struts.devMode" value="true"/> 18 <!-- 引入关联配置文件 --> 19 <include file="struts-json.xml"/> 20 <include file="struts-upload.xml"/> 21 <include file="struts-download.xml"/> 22 </struts>
struts-download.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <constant name="struts.multipart.maxSize" value="1000000000"/> 7 <package name="bamaw_download" namespace="/" extends="struts-default"> 8 <action name="stream" class="com.tbamaw.web.action.DownLoadAction"> 9 <result type="stream" name="success"> 10 <param name="contentDisposition">attachment;filename=${filename}</param> 11 </result> 12 </action> 13 </package> 14 </struts>
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="${pageContext.request.contextPath }/stream.action?filename=baba.jpg">下载</a> 11 </body> 12 </html>
servlet-api的方式文件下载
1.建立DownLoadAction
2.配置struts.xml
3.发送文件下载请求
时间: 2024-10-24 13:49:48