解决 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

相关文章
相关标签/搜索