java 文件下載中文亂碼問題。期初我認爲是不通瀏覽器的兼容問題,但是實際上就是。看下面一段代碼
/**
* 文件下載
* @param response
* @param filePath
*/
public void fileDownLoad(HttpServletResponse response,String filePath){
File f = new File(filePath);
if(!f.exists()){
System.out.println("==下載文件不存在=="+filePath);
return;
}
String fileName = f.getName();//文件名
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
InputStream is = null;
OutputStream os = null;
try {
System.out.println("===fileDowload==文件名:"+fileName);
//String tempFileName =new String(fileName.getBytes("utf-8"),"ISO-8859-1");
String tempFileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition","attachment;fileName="+tempFileName);//設置響應的文件名
response.setHeader("Content-Length",String.valueOf(f.length()));//設置文件大小
is = new FileInputStream(new File(filePath));
os = response.getOutputStream();
byte[] b = new byte[1024];
int length=0;
while((length=is.read(b))>0){
os.write(b, 0, length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(is != null)
is.close();//關閉流
if(os != null)
os.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
這段下載的代碼在瀏覽器谷歌、火狐下都是正常的,但是在IE下卻會亂碼。開始也考慮過轉碼:
String tempFileName =new String(fileName.getBytes("utf-8"),"ISO-8859-1");
但是問題沒有解決。做前端與瀏覽器的兼容戰鬥從沒有停止過。最終看到別人帶的微博,找到了一種兼容的方法:
response.setHeader("Content-Disposition","attachment;fileName=\""+tempFileName+"\"");//設置響應的文件名
這個方法並沒有做全面的測試,但是目前的問題已解決。