标签:code pre 注意 ref except default down efault round
1.在实际应用开发中,文件下载功能也非常常见。
2.最简单的文件下载方式是通过超链接来进行文件下载:
<body> <a href="download/s.txt">课件</a><br/> <a href="download/t.jpg">美女</a><br/> <a href="download/jstl-1.2.jar">jstl</a> </body>
注意:直接通过超链接下载文件,如果浏览器能够读取文件,浏览器会直接读取,而不会下载到本地。并且有安全问题。所以,可以通过action来实现下载。
3.Struts2文件下载功能的实现:
Action实现
public class DownloadAction { private String fileName; public String execute(){ return Action.SUCCESS; } //获取文件流 public InputStream getInputStream() throws FileNotFoundException{ String path=ServletActionContext.getServletContext().getRealPath("/download"); return new FileInputStream(new File(path,fileName)); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
Struts.xml
<package name="default" extends="struts-default" namespace="/"> <action name="download" class="cn.sxt.action.DownloadAction"> <result type="stream"> <!-- 根据inputName生产的get方法 到Action中去取得该方法的返回值 --> <param name="inputName">inputStream</param> <!-- 设置下载的文件 直接保存 --> <param name="contentDisposition">attachment;filename=${fileName}</param> </result> </action> </package>
jsp
<body> <a href="download/2.txt">课件</a> <br /> <a href="download/1.jpg">美女</a> <br /> <hr /> <a href="download.action?fileName=2.txt">课件</a> <br /> <a href="download.action?fileName=1.jpg">美女</a> <br /> </body>
或者 Action的另一种写法:
public class DownloadAction { private String fileName; private InputStream inputStream; public String execute() throws FileNotFoundException{ String path=ServletActionContext.getServletContext().getRealPath("/download"); inputStream = new FileInputStream(new File(path,fileName)); return Action.SUCCESS; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
标签:code pre 注意 ref except default down efault round
原文地址:https://www.cnblogs.com/Vincent-yuan/p/11161226.html