目前支持ie9-11,firefox63.0,chrome69.0,qq10.2.1的版本,safari的最新版本(特别是解决mac下的safari中,下载文件的中文文件名问题)。
下载文件时, 设置Content-Disposition。对于较新的 Firefox 、 Chrome 、 Opera 、 Safari 等浏览器,都支持新标准规定的 filename* ,并且会优先使用,所以尽管 filename=”encoded_text” 不被它们支持,仍然不会有问题;至于使用 UTF-8 只是因为它是标准中强制要求必须支持的。而对于旧版本的IE浏览器,它们无法识别后面的 filename* ,会自动忽略并使用旧的 filename 。这样一来就完美解决了多浏览器的多语言兼容问题,不需要 UA 判断。
result.Content.Headers.Add("content-disposition",
string.Format("attachment;filename={0};filename*=utf-8''{0}", HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
注意的下载文件的时候,safari需要显性指定Mime ,之前默认是"application/octet-stream",只兼容了非safari浏览器。
代码如下:
switch (Path.GetExtension(fileName).ToLower())
{
case ".xlsx": fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
case ".docx": fileType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
case ".pptx": fileType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; break;
case ".pdf": fileType = "application/pdf"; break;
case ".jpg": fileType = "image/jpeg"; break;
case ".jpeg": fileType = "image/jpeg"; break;
case ".png": fileType = "image/png"; break;
default: break;
}
参考:
https://blog.robotshell.org/2012/deal-with-http-header-encoding-for-file-download/