解決 ie 下載文件名 中文亂碼

// response以文件流返回附件
public void getDownload(String fullPath, HttpServletRequest request, HttpServletResponse response) throws IOException {

   // Get your file stream from wherever.
   File downloadFile = new File(fullPath);
   ServletContext context = request.getServletContext();
   // get MIME type of the file
   String mimeType = context.getMimeType(fullPath);
   if (mimeType == null) {
      // set to binary type if MIME mapping not found
      mimeType = "application/octet-stream";
      System.out.println("context getMimeType is null");
   }
   System.out.println("MIME type: " + mimeType);
   // set content attributes for the response
   response.setContentType(mimeType);
   response.setContentLength((int) downloadFile.length());
   response.setCharacterEncoding("UTF-8");
   // set headers for the response
   String headerKey = "Content-Disposition";

   //String guessCharset = request.getCharacterEncoding(); /* 根據request的locale 得出可能的編碼,中文操做系統一般是gb2312 */
   //String fileName = new String(downloadFile.getName().getBytes(guessCharset), "utf-8");
String headerValue = "attachment; filename=" + URLEncoder.encode(downloadFile.getName(), "utf-8")
                                                   .replaceAll("\\+", "%20")
                                                   .replaceAll("%28", "\\(")
                                                   .replaceAll("%29", "\\)")
                                                   .replaceAll("%3B", ";")
                                                   .replaceAll("%40", "@")
                                                   .replaceAll("%23", "\\#")
                                                   .replaceAll("%26", "\\&")
                                                   .replaceAll("%2C", "\\,");
response.setHeader(headerKey, headerValue);

   // Copy the stream to the response's output stream.
   InputStream myStream = null;
   try {
      myStream = new FileInputStream(fullPath);
      IOUtils.copy(myStream, response.getOutputStream());
      response.flushBuffer();
   } catch (IOException e) {
      e.printStackTrace();
   } finally {
      if (myStream != null) {
         myStream.close(); // 關閉流
      }
   }
}

 

new String(downloadFile.getName().getBytes(guessCharset), "iso-8895-01");app

不要用這種,不行的編碼

URLEncoder.encode(downloadFile.getName(), "utf-8")操作系統

直接這樣就能夠了,J8問題code

相關文章
相關標籤/搜索