struts2 之 文件下載


1. 文件下載在應用系統使用也很常見。圖片的下載,文件的下載,電影的下載。文件下載可以非常簡單,通過超鏈接就可以直接下載。

<body>
   <a href="download/t.txt">誅仙</a><br/>
   <a href="download/jstl-1.2.jar">struts的jar包</a>
  </body>

但是通過超鏈接下載有一下問題:

如果瀏覽器能夠讀取文件,將會在瀏覽器中直接打開。沒有好的方式來控制用戶是否有權限下載。

2. 通過流的下載方式可以解決超鏈接的不足。實現步驟:

a) 編寫Action

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:

<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的第二種寫法:

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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM