Struts2之文件下载

        在上一篇文章中我们说过了文件上传,与之相对的则是文件下载,碰到这个我们该如何处理呢?下面就来看看如何进行文件下载:
还是老样子,先来看看下载一个文件,请往下看:
一、下载一个文件
1、downloadFile.jsp
<body>
    <a href="downloadFile.action">download</a> <br>
</body>
2、struts.xml
     < struts >
        <action name="downloadFile" class="com.tgb.struts2.DownloadAction">
            <result type="stream">
                <param name="contentDisposition">attachment;filename="session1.bmp"</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
</struts>
3、 DownloadAction
     public   class  DownloadAction  extends  ActionSupport {
    public InputStream getDownloadFile(){
        return ServletActionContext.getServletContext()
                .getResourceAsStream("/upload/session1.bmp");
    }
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
}
二、如果有多个文件要下载,则看下面
1、downloadFile.jsp
<body>
     < a href="downloadFile2.action?num=1" > download2.1 </ a >   < br >
    <a href="downloadFile2.action?num=2">download2.2</a> <br> 
</body>
2、struts.xml
     < struts >
        <action name="downloadFile" class="com.tgb.struts2.DownloadAction">
            <result type="stream">
                <param name="contentDisposition">attachment;filename="   ${fileName} "</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
</struts>
3、 DownloadAction
     public   class  DownloadAction  extends  ActionSupport {
     private   int  num;
    private String fileName;
     //get、set方法省略...
   
    public InputStream getDownloadFile(){
         try  {
            if (1==num){
                this.fileName="session1.bmp";
                //如果下载文件是中文名称的,则会出现字符乱码,加上下面这句话则可以规避字符乱码
                this.fileName=new String(this.getFileName().getBytes("gbk"),"8859_1");
                
                return ServletActionContext.getServletContext()
                        .getResourceAsStream("/upload/session1.bmp");
            }else{
                this.fileName="1.txt";
                return ServletActionContext.getServletContext()
                        .getResourceAsStream("/upload/1.txt");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }  
}
   

你可能感兴趣的:(ssh,struts2.0)