使用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>
注:其中参数param中contentType、contentDisposion和inputName是必须的,而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