下载文件名称乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dongyuxu342719/article/details/84955192

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

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

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

In the extended BNF notation of [RFC 822], the Content-Disposition
   header field is defined as follows:

        disposition := "Content-Disposition" ":"
                       disposition-type
                       *(";" disposition-parm)

        disposition-type := "inline"
                          / "attachment"
                          / extension-token
                          ; values are not case-sensitive

        disposition-parm := filename-parm / parameter

        filename-parm := "filename" "=" value;

   `Extension-token', `parameter' and `value' are defined according to
   [RFC 822] and [RFC 1521].

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

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

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

猜你喜欢

转载自blog.csdn.net/dongyuxu342719/article/details/84955192