檔案下載firefox瀏覽器和chrom瀏覽器中文名不顯示問題
*檔案下載firefox瀏覽器中文名不顯示問題
*/
public class ServletDemo5 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//檔案下載中文檔名不顯示的問題
String path = this.getServletContext().getRealPath("/你好.jpg");//獲取檔案的絕對路徑
String filename = path.substring(path.lastIndexOf("\\")+1); //擷取檔名
String displayName = URLEncoder.encode(filename,"utf-8");//用utf-8的格式編碼
if ("FF".equals(getBrowser(request))) {
// 針對火狐瀏覽器處理方式不一樣了
displayName = new String(filename.getBytes("UTF-8"),
"iso-8859-1");
}
response.setHeader("content-disposition", "attachment;filename="+displayName);
InputStream in = new FileInputStream(path);
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b))>0){
os.write(b,0,len);
}
}
// 以下為伺服器端判斷客戶端瀏覽器型別的方法
private String getBrowser(HttpServletRequest request) {
String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
if (UserAgent != null) {
if (UserAgent.indexOf("msie") >= 0)
return "IE";
if (UserAgent.indexOf("firefox") >= 0)
return "FF";
if (UserAgent.indexOf("safari") >= 0)
return "SF";
}
return null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}