Response.setHeader("Content-Disposition", "attachment; filename=" + fileName+".xls");
如果file.Name為中文則亂碼。解決辦法是
方法1:
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
下載的程式裡有了上面一句,一般在IE6的下載提示框上將正確顯示檔案的名字,無論是簡體中文,還是日文。但是文字只要超過17個字,就不能下載了。
一. 通過原來的方式,也就是先用URLEncoder編碼,當中文文字超過17個時,IE6 無法下載檔案。這是IE的bug,參見微軟的知識庫文章 KB816868 。原因可能是IE在處理 Response Header 的時候,對header的長度限制在150位元組左右。而一個漢字編碼成UTF-8是9個位元組,那麼17個字便是153個位元組,所以會報錯。而且不跟尾碼也不對.
方法2:
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
在確保附件檔案名稱都是簡 體中文字的情況下,那麼這個辦法確實是最有效,不用讓客戶逐個的升級IE。如果台灣同胞用,把gb2312改成big5就行。但現在的系統通常都加入了 國際化的支援,普遍使用UTF-8。如果檔案名稱中又有簡體中文字,又有繁體中文,還有日文。那麼亂碼便產生了。另外,在上Firefox (v1.0-en)下載也是亂碼。
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page contentType="text/html;charset=GBK"%>
<%
String key = request.getParameter("key");
String title = request.getParameter("file");
if(title == null) title="downLoad_table";
title += ".xls";
System.out.println("JILNJJHXJKHJHJHJHJ"+title);
if(key != null && !key.equals(""))
{
response.setContentType("application/x-msdownload");
response.setHeader("Content-type","application/x-msdownload");
response.setHeader("Accept-Ranges","bytes");
response.setHeader("Content-Disposition","attachment; filename="+ java.net.URLEncoder.encode(title, "UTF-8"));
String str = (String) session.getAttribute(key);
OutputStream os = response.getOutputStream();
String header = "<html><head><title></title>\n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html;charset=GBK\">\n" +
"<meta name=ProgId content=Excel.Sheet>\n" +
"<style>\n" +
"<!--\n" +
"a {\n" +
"font-size: 9pt;\n" +
"color: navy;\n" +
"text-decoration: none;\n" +
"}\n" +
"a:hover {\n" +
"font-size: 9pt;\n" +
"color: darkorange;\n" +
"text-decoration: underline;\n" +
"}\n" +
"-->\n" +
"</style>\n" +
"</head>\n" +
"<body>\n";
os.write(header.getBytes("GBK"));
os.write(str.getBytes("GBK"));
os.write("</body></html>".getBytes("GBK"));
os.flush();
os.close();
session.removeAttribute(key);
return;
}
else
{
session.removeAttribute(key);
%>
<html>
<!--
/*****************************************************************************
* function:
* Version 1.0
* Author: leo Leo.Chou decay@163.com
* create time : 2006.06.01
* You can copy and/or use and/or modify this program free,but please reserve
* the segment above. Please mail me if you have any question, Good day!
*****************************************************************************
*/
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title></title></head>
<body bgcolor="#F0FAFF" text="#FF8040" marginwidth="0" marginheight="0" leftmargin="5" topmargin="1">
<script language="JavaScript">
<!--
alert("下載統計表錯誤。");
-->
</script>
</body></html>
<%
return;
}
%>