1. 文件下載在應用系統使用也很常見。圖片的下載,文件的下載,電影的下載。文件下載能夠很是簡單,經過超連接就能夠直接下載。瀏覽器
<body> <a href="download/t.txt">誅仙</a><br/> <a href="download/jstl-1.2.jar">struts的jar包</a> </body>
可是經過超連接下載有一下問題:jsp
若是瀏覽器可以讀取文件,將會在瀏覽器中直接打開。沒有好的方式來控制用戶是否有權限下載。this
2. 經過流的下載方式能夠解決超連接的不足。實現步驟:spa
a) 編寫Action
code
public class DownloadAction extends ActionSupport{ private String fileName; //獲取文件流 public InputStream getInputStream() throws IOException{ String path = ServletActionContext.getRequest().getRealPath("/download"); return new FileInputStream(new File(path,fileName)); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
b)配置action:blog
<action name="download" class="cn.sxt.action.DownloadAction"> <result type="stream"> <param name="inputName">inputStream</param> <param name="contentDisposition">attachment;filename=${fileName}</param> </result> </action>
c)jsp圖片
<a href="download.action?fileName=t.txt">誅仙</a><br/> <a href="download.action?fileName=jstl-1.2.jar">struts的jar包</a>
3.文件下載Action的第二種寫法:get
public class DownloadAction extends ActionSupport{ private String fileName; private InputStream inputStream; public String execute()throws IOException{ String path = ServletActionContext.getRequest().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; } }