springmvc中下載中文文件名稱為下劃線的解決方案

springmvc下載中文文件名稱為下劃線

springboot項目中,在下載文件的時候,通過封裝ResponseEntity,將文件流寫入body,這種下載文件的方式,造成瞭下載的文件名為正文顯示為下劃線的形式;

這個問題很好解決

直接將輸入的文件名的編碼格式定義成GBK格式;

如下代碼

public static ResponseEntity<FileSystemResource> export(File file) throws UnsupportedEncodingException {
        if (file == null) {
            return null;
        }
        //這個位置對文件名進行編碼
        String fileName = new String (file.getName().getBytes("GBK"),"ISO-8859-1");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" +fileName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

java生成文件名時漢字變為下劃線?

public static void exportToExcel(String uid, String name, String htmlText, 
HttpServletRequest request, HttpServletResponse response) {
      htmlText = htmlText.replaceFirst("<table>", "<tableFirst>");
      htmlText = htmlText.replaceAll("<table>",
            "<table cellpadding=\"3\" cellspacing=\"0\"  border=\"1\" rull=\"all\" 
style=\"border-collapse: collapse\">");
      htmlText = htmlText.replaceFirst("<tableFirst>", "<table>");
      try (OutputStream out = response.getOutputStream()) {
         String fileName = name+ "_" + DateUtils.getNow("yyyyMMddHHmmss");
//       fileName = new String(fileName.getBytes(),"utf-8")+ ".xls";
         if ("large".equals(htmlText)) {
            ReportingPo report = reportingService.getByUid(uid);
            Map<String, Object> formParameters = generationService.getFormParameters(request.getParameterMap(), 
report.getDataRange());
            ReportTable reportTable = generationService.getReportTable(report, formParameters);
            htmlText = reportTable.getHtmlText();
         }
//       response.reset();
         response.addHeader("Content-Disposition", "attachment;filename=" +
 new String(fileName.getBytes("utf-8"),"iso-8859-1")+ ".xls");
//       response.setHeader("Content-Disposition", String.format("attachment; filename=%s", fileName));
         response.setContentType("application/vnd.ms-excel; charset=utf-8");
         response.setCharacterEncoding("utf-8");
         response.addCookie(new Cookie("fileDownload", "true"));
//       out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); // 生成帶bom的utf8文件
         out.write(htmlText.getBytes("utf-8"));
         out.flush();
      } catch (Exception ex) {
         throw new RuntimeException(ex);
      }
   }

註意這裡兩個編碼

new String(fileName.getBytes("utf-8"),"iso-8859-1")+ ".xls"

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: