struts2文件下载(实现模板下载)

项目中的一个应用,提供模板下载。

jsp页面:

<a href="#" id="downLoadTemplate"><span>模板下载</span></a>


对应的js部分,负责触发事件:

$('#downLoadTemplate').click(function(){
location.href = contextPath + '/libprodmgr/billFormat/downLoadBillFormat.action';
});


action 中代码部分:

//下载文件的文件名
private String downLoadFileName;

public String getDownLoadFileName() {
return downLoadFileName;
}

public void setDownLoadFileName(String downLoadFileName) {
this.downLoadFileName = downLoadFileName;
}

//从下载文件原始存放路径读取得到文件输出流
public InputStream getDownloadFile() {
return ServletActionContext.getServletContext().getResourceAsStream("/common/excelModule/你的文件名.xls");
}

public String downLoadBillFormat() {

try {
//因为我们是URL的请求去下载文件,所以用URL编码,这样可保证中文名称不会乱码。
downLoadFileName = URLEncoder.encode("你的文件名.xls", "UTF-8");
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename=" + downLoadFileName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

return SUCCESS;
}


之前自己是用下面这种方法去解决中文乱码问题的,但是发现在tomcat下是不会乱码,而在WebLogic下还是会乱码,所以还是上面那种URL编码可靠一点。

public String downLoadBillFormat() {

try {
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="
+ new String("你的文件名.xls".getBytes(), "iso-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

return SUCCESS;
}


xml配置文件部分:

<action name="downLoadBillFormat" class="billFormatAction" method="downLoadBillFormat">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;fileName=${downLoadFileName}</param>
<param name="inputName">downloadFile</param>
</result>
</action>



在xml的配置文件中,
<param name="inputName">downloadFile</param>

中的“downloadFile”必须对应action中的方法名“getDownloadFile”。

有一个问题,在xml中

<param name="contentDisposition">attachment;fileName=${downLoadFileName}</param>

中的“fileName”,我发现改为“filename”也一样可以下载,不会有问题,谁能告诉我这其中有没有什么区别呢?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值