Content-Disposition中的filename进行了两次URL转码。以汉字漫为例:
第一次转码,漫变为%E6%BC%AB。
第二次转码,%E6%BC%AB变为%25E6%25BC%25AB(第二次转码时,因为%是特殊字符,所以会转为%25)。
前端下载时:
Chrome浏览器可以自动执行两次URL解码,所以下载的文件名是正常的。
IE浏览器只执行一次URL解码,所以下载的文件名是第一次编码的结果(%E6%BC%AB)(版本8,10验证问题存在)。
火狐好像也不行。
解决方案是在返回给前端前对Content-Disposition中的filename先进行一次URL解码(实际我是对filename这个参数进行了解码,因为文件服务器是用的第三方的。)。
此外,当文件名为中文(未执行URL编码)字符串时,IE下载也为乱码,因为IE对中文字符串又执行了一次URL解码。解决方案是将中文字符串进行URL编码。
所以,总结下来,关键的问题就在于IE浏览器对filename只进行一次解码,而chrome对这种情况是进行了优化的
file_name = self.opts.verbose_name.replace(' ', '_')
browser_type = self.request.META['HTTP_USER_AGENT'].upper()
if 'MSIE' in browser_type or 'TRIDENT' in browser_type or 'EDGE' in browser_type:
response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
file_name, file_type))
else:
response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
file_name, file_type)).encode('utf-8')