實例:瀏覽器
String poorName= dataMap.get("NAME").toString();
String villageName = dataMap.get("ADDRESS").toString();
String filename=villageName+"-"+poorName+".doc";
response.setContentType("application/doc");
final String userAgent = request.getHeader("USER-AGENT");
if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
filename = URLEncoder.encode(filename,"UTF-8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
filename = new String(filename.getBytes(), "ISO8859-1");
}else{
filename = URLEncoder.encode(filename,"UTF-8");//其餘瀏覽器
}
response.addHeader("Content-Disposition", "attachment;filename="
+filename);/這裏設置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開
Writer out = response.getWriter();app
也能夠直接把方法提取出來供之後直接使用:函數
setFileDownloadHeader函數主要是根據當前用戶的瀏覽器不一樣,對文件的名字進行不一樣的編碼設置,從而解決不一樣瀏覽器下文件名中文亂碼問題google
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
final String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
finalFileName = URLEncoder.encode(fileName,"UTF8");//其餘瀏覽器
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//這裏設置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開
} catch (UnsupportedEncodingException e) {
}
}編碼