struts2实现文件下载

使用struts2实现文件的下载:

1、 首先编写jsp页面

<a href=”download.action?filename=Java容器.ppt”>down</a>

将encoding改为utf-8

2、 编写后台action

接收filename参数

private String filename;

    public String getFilename() {

        returnfilename;

    }

    publicvoid setFilename(Stringfilename) {

        this.filename = filename;

    }

    一下是乱码的处理:

    /*

    public String getChineseFile(){

        Stringchine=filename;

        try {

            chine= newString(chine.getBytes("ISO-8859-1"),"utf-8");

            System.out.println(chine);

        }catch(UnsupportedEncodingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

       

        return chine;

    }

*/

返回一个文件流:

public InputStream getDownloadFile(){

return ServletActionContext.getServletContext().getResourceAsStream("/"+getChineseFile());

    }

3、 Struts2.xml进行配置

<action name="download"class="cn.DownloadAction">

            <result name="success" type="stream">

               

<param name="contentType">application/powerpoint</param>

                <param name="contentDisposition">attachment;filename="${chineseFile}"  </param>

                <param name="inputName">downloadFile</param>

            </result>

        </action>

注:其中参数paramcontentTypecontentDisposioninputName是必须的,而inputName中的值是返回类型为InputStream的方法去掉get,即注意黑体部分

4、 出现下载界面,不进行下载而是点击出现取消出现异常:

解决方法:下载包,添加到webroot的lib下,并把struts.xml进行修改

<result-types> 

            <result-type   name="streamx" class="com.sunspoter.lib.web.struts2.dispatcher.StreamResultX"/> 

         </result-types>  

        <action name="download" class="cn.DownloadAction">

            <result name="success" type="streamx">

           

               

                <param name="contentType">application/powerpoint</param>

                <param name="contentDisposition">attachment;filename="${chineseFile}"  </param>

                <param name="inputName">downloadFile</param>

            </result>

    </action>

增加一个result-type属性,result中的type值设为streamx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值