【问题标题】:How to display illegal characters on downloaded file name in Spring?Spring中如何在下载的文件名上显示非法字符?
【发布时间】:2019-11-12 21:51:11
【问题描述】:

我下载的文件名变为 Ça_r_lar_02_07_2019_12_09.xlsx,但是,我想要它 Çağrılar_02_07_2019_12_09.xlsx。我该如何解决?

try (Workbook workbook = new XSSFWorkbook()) {
                new XlsExporter().exportXls(workbook, grh);
                SimpleDateFormat sdf = new SimpleDateFormat("_dd_MM_yyyy_HH_mm");
                String name = grh.getReportName() + sdf.format(new Date());
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM.getType());
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name +  ".xlsx\"");
                workbook.write(response.getOutputStream());
                response.getOutputStream().flush();
            }

【问题讨论】:

  • 你确定底层文件系统(操作系统)支持文件名中的这些字符?!
  • @GhostCat 是的,它支持
  • 您是否尝试过使用此处所示的相应 unicode 字符直接对您的 name 变量进行编码? :stackoverflow.com/questions/5585919/… 例如你的 c 应该是 u00c7

标签: java spring


【解决方案1】:

在发送响应之前尝试对您的文件名进行 UTF-8 编码

try (Workbook workbook = new XSSFWorkbook()) {
                new XlsExporter().exportXls(workbook, grh);
                SimpleDateFormat sdf = new SimpleDateFormat("_dd_MM_yyyy_HH_mm");
                String name = grh.getReportName() + sdf.format(new Date());
                name = URLEncoder.encode(name,"UTF-8"); 
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM.getType());
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name +  ".xlsx\"");
                workbook.write(response.getOutputStream());
                response.getOutputStream().flush();
            }

【讨论】:

  • 这是正确的,因为根据 HTTP 标准,在实际内容之前发送的标头行是 ISO-8859-1。
  • 空白变成“+”字符,你知道这是为什么吗?
  • 那是因为 URL 编码。您可以将.replaceAll("\\+", "%20") 附加到您的 URLEncoder 函数。或者使用使用 RFC 2396 的 URI 类(或 Spring 中的 URIUtils)。更多信息可以在这里找到:en.wikipedia.org/wiki/Percent-encoding
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2019-10-15
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多