在很多下载系统中我们都会使用这样一种策略:隐藏真实文件位置,而通过一个Servlet或jsp最为下载接口以便进行防盗链或权限管理;
另一些时候,我们希望浏览器客户直接下载一个文档(比如gif图片)而不是在浏览器中打开;这些时候我们可以通过在http header中加入Content-Disposition节来解决。
基本代码:
response.setHeader("Content-Disposition", "attachment;filename=
yourfilename.");
但是
如果
ourfilename是中文的话,在客户端就会是乱码

通过在网上查资料我知道应该如下修改
response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode("
yourfilename","utf-8"));
我在firefox下试了一下发现是这样:

于是在网上又查,然后经过测试发现可以这么作
response.setHeader("Content-Disposition", "attachment;filename="+ new String("
yourfilename".getBytes("UTF-8"),"ISO8859-1") );
但同样的代码在ie中依旧是乱码,ie中需要这么作:
response.setHeader("Content-Disposition", "attachment;filename="+ new String("
yourfilename".getBytes(),"ISO8859-1") );
说明header中可以且必须使用iso8859-1的字符集字符,ie默认是向gbk(本机默认编码)解码,ff默认是向utf-8解码。于是只好这么作了:
if (request.getHeader("user-agent")!=null && request.getHeader("user-agent").indexOf("MSIE")<0)
{
//not ie
response.setHeader("Content-Disposition", "attachment;filename="+ new String("中文".getBytes("UTF-8"),"ISO8859-1") +".txt");
}
else
{
//ie
response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode("中文","utf-8") +".txt");
}
试了试,通过!:)
Trackback: http://tb.donews.net/TrackBack.aspx?PostId=309672