I set like this:
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("你好.txt", "utf-8"));
it works in chrome, but not in firefox, in firefox the file name is %E4%BD%A0%E5%A5%BD.txt
.
So how to set file name? I want the file name to be showed correctly in chrome, firefox and IE(>=8)
PS:solved by a friend, share it with you, maybe it can help others.
/**
return encoded file name
*/
protected String getFileName(String filename) {
try{
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
if (request.getHeader("User-Agent").indexOf("MSIE") != -1) {
return '\"' + java.net.URLEncoder.encode(filename, "UTF-8") + '\"';
}
byte[] bytes = filename.getBytes("UTF-8");
StringBuilder buff = new StringBuilder(bytes.length << 2);
buff.append("=?UTF-8?Q?");
for (byte b : bytes) {
int unsignedByte = b & 0xFF;
buff.append('=').append(HEX_CHARS[unsignedByte >> 4]).append(HEX_CHARS[unsignedByte & 0xF]);
}
return buff.append("?=").toString();
}catch(UnsupportedEncodingException e){
return filename;
}
}
private static final char[] HEX_CHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F' };
I test this code in chrom 33.0, IE 8 and firefox 26.0, it works well.