我實現了一個簡單的文件上傳 - 下載機制。當用戶單擊文件名時,文件將使用這些HTTP標頭下載:文件下載(IE)時文件名損壞
HTTP/1.1 200 OK
Date: Tue, 30 Sep 2008 14:00:39 GMT
Server: Microsoft-IIS/6.0
Content-Disposition: attachment; filename=filename.doc;
Content-Type: application/octet-stream
Content-Length: 10754
我還支持日文文件名。爲了做到這一點,我編碼的文件名與該Java方法:
private String encodeFileName(String name) throws Exception{
String agent = request.getHeader("USER-AGENT");
if(agent != null && agent.indexOf("MSIE") != -1){ // is IE
StringBuffer res = new StringBuffer();
char[] chArr = name.toCharArray();
for(int j = 0; j < chArr.length; j++){
if(chArr[j] < 128){ // plain ASCII char
if (chArr[j] == '.' && j != name.lastIndexOf("."))
res.append("%2E");
else
res.append(chArr[j]);
}
else{ // non-ASCII char
byte[] byteArr = name.substring(j, j + 1).getBytes("UTF8");
for(int i = 0; i < byteArr.length; i++){
// byte must be converted to unsigned int
res.append("%").append(Integer.toHexString((byteArr[i]) & 0xFF));
}
}
}
return res.toString();
}
// Firefox/Mozilla
return MimeUtility.encodeText(name, "UTF8", "B");
}
它運作良好,到目前爲止,直到有人發現它不長文件名很好地工作。例如:あああああああああああああああ2008.10.1あ.doc
。如果我將其中一個單字節點更改爲單字節下劃線,或者如果我刪除第一個字符,則它可以正常工作。即它取決於點字符的長度和URL編碼。 以下是一些例子。
這是打破(あああああああああああああああ2008.10.1あ.doc
):
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
這是OK(あああああああああああああああ2008_10.1あ.doc
):
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008_10%2E1%e3%81%82.doc;
這也是精(あああああああああああああああ2008.10.1あ.doc
):
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
人有一個線索?
恭喜!有時候,人們可以得到的最佳答案根本就沒有答案,這迫使我們再次審視這個問題 - 當你自己解決問題時,這會帶來更多的回報;) – 2008-09-30 15:49:49
參見https://stackoverflow.com/q/93551/ 3995261('* = UTF-8''bit) – YakovL 2018-02-04 13:36:39