解決方案瀏覽器
針對不一樣瀏覽器類型,對文件名字作編碼處理 Firefox (Base64) ;IE、Chrome ... 使用的是URLEncodertomcat
public class DownloadServlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取文件在tomcat下的路徑 String path = getServletContext().getRealPath("download/測試文檔.txt"); String fileName = "測試文檔.txt"; String clientType = req.getHeader("User-Agent"); System.out.println(clientType); if(clientType.contains("Firefox")){ fileName = base64EncodeFileName(fileName); }else{ //IE ,或者 Chrome (谷歌瀏覽器) , //對中文的名字進行編碼處理 fileName = URLEncoder.encode(fileName,"UTF-8"); } //讓瀏覽器收到這份資源的時候, 如下載的方式提醒用戶,而不是直接展現 resp.setHeader("Content-Disposition", "attachment; filename="+fileName); //轉化成輸入流 InputStream is = new FileInputStream(path); OutputStream os = resp.getOutputStream(); int len = 0; byte[] bts = new byte[1024]; while ((len = is.read(bts)) != -1) { os.write(bts, 0, len); } os.close(); is.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } public String base64EncodeFileName(String fileName) { BASE64Encoder base64Encoder = new BASE64Encoder(); try { return "=?UTF-8?B?" + new String(base64Encoder.encode(fileName .getBytes("UTF-8"))) + "?="; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } } }