判斷各個瀏覽器,然後進行解碼和加碼 ...
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 String browser = ""; 4 String fileName = "測試.txt"; 6 try { 7 browser = request.getHeader("User-Agent"); 8 if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) { 9 // IE6, IE7 瀏覽器 10 response.addHeader("content-disposition", "attachment;filename=" 11 + new String(fileName.getBytes(), "ISO8859-1")); 12 } else if (-1 < browser.indexOf("MSIE 8.0")) { 13 // IE8 14 response.addHeader("content-disposition", "attachment;filename=" 15 + URLEncoder.encode(fileName, "UTF-8")); 16 } else if (-1 < browser.indexOf("MSIE 9.0")) { 17 // IE9 18 response.addHeader("content-disposition", "attachment;filename=" 19 + URLEncoder.encode(fileName, "UTF-8")); 20 } else if (-1 < browser.indexOf("Chrome")) { 21 // 谷歌 22 response.addHeader("content-disposition", 23 "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); 24 } else if (-1 < browser.indexOf("Safari")) { 25 // 蘋果 26 response.addHeader("content-disposition", "attachment;filename=" 27 + new String(fileName.getBytes(), "ISO8859-1")); 28 } else { 29 // 火狐或者其他的瀏覽器 30 response.addHeader("content-disposition", 31 "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); 32 } 33 } catch (Exception e) { 34 e.printStackTrace(); 35 } 36 InputStream in = new FileInputStream("D:\\test.txt");//獲取文件輸入流 37 int len = 0; 38 byte[] buffer = new byte[1024]; 39 OutputStream out = response.getOutputStream(); 40 while ((len = in.read(buffer)) > 0) { 41 out.write(buffer,0,len);//將緩衝區的數據輸出到客戶端瀏覽器 42 } 43 in.close(); 44 out.flush(); 45 out.close(); 46 }
判斷各個瀏覽器,然後進行解碼和加碼