下载文件名称乱码问题

阳光穿透心脏的1/2处 2022-04-05 07:40 323阅读 0赞

后台使用FtpClient类获取服务器上的文件字节流传给Response对象的输出流属性来下载文件,响应头设置如下:

  1. response.setContentType("multipart/form-data");
  2. response.setHeader("Content-Disposition", "attachment;fileName="+fileName;

filename是存储的真实文件名,在下载包含中文名的文件时会出现乱码。RFC1806可以看到Content-Disposition头的定义:

  1. In the extended BNF notation of [RFC 822], the Content-Disposition
  2. header field is defined as follows:
  3. disposition := "Content-Disposition" ":"
  4. disposition-type
  5. *(";" disposition-parm)
  6. disposition-type := "inline"
  7. / "attachment"
  8. / extension-token
  9. ; values are not case-sensitive
  10. disposition-parm := filename-parm / parameter
  11. filename-parm := "filename" "=" value;
  12. `Extension-token', `parameter' and `value' are defined according to
  13. [RFC 822] and [RFC 1521].

其中规定了Content-Disposition的格式,RFC5987中的3.2和4小节给出了通用表达式和字符编码例子,因此我们可以通过设置文件名的编码为utf-8来避免和前端浏览器不一致导致的乱码,现在的请求头设置如下:

  1. response.setContentType("multipart/form-data");
  2. response.setHeader("Content-Disposition", "attachment;fileName="+fileName;

Chrome测试有效,其他浏览器没有测试。

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读