一般情況下,大家都是這樣:
fileName = URLEncoder.encode(fileName, "UTF-8"); response.reset(); response.setHeader("Content-disposition", "attachment;filename=" + fileName); response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.copy(inputStream, response.getOutputStream());
其實(shí)亂碼就是亂在;filename=" + fileName這里,對文件名的編碼設(shè)定上。
使用URLEncoder.encode(filepath,"UTF-8")雖然可以解決在提示下載框中正確顯示漢字文件名的問題,并且在選擇保存,然后打開的情況下,文件名稱也可以正確的顯示。
但是在提示下載框中,選擇直接打開,則文件名稱變成了類似“%E7%BB%99%E7%94%A8%E6%88%B7%E6%8F%90%E4%BE%9B%E7%9A%84%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6%E5%90%8D”的樣子。
為了解決這個問題,百度了好久,是這樣的
String downloadfile = new String(filepath.getBytes("gb2312"),"iso8859-1");
response.addHeader("Content-Disposition","attachment;filename=" + downloadfile );
還有這樣
String userAgent = request.getHeader("User-Agent");
String formFileName = "員工表.xls";
// 針對IE或者以IE為內(nèi)核的瀏覽器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
? ? formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
} else {
? ? // 非IE瀏覽器的處理:
? ? formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", formFileName));
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
?
發(fā)現(xiàn)都不能解決問題,不懈努力,崩潰邊緣,最終解決文章來源:http://www.zghlxwxcb.cn/news/detail-662397.html
fileName = URLEncoder.encode(fileName, "UTF-8"); response.reset(); // fileName后面設(shè)置編碼格式是重點(diǎn) response.setHeader("Content-disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName); response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.copy(inputStream, response.getOutputStream());
完美解決?。。?span toymoban-style="hidden">文章來源地址http://www.zghlxwxcb.cn/news/detail-662397.html
到了這里,關(guān)于Java下載文件,中文文件名亂碼問題解決(文件名包含很多%)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!