
通过流的下载的方式下载文件的需求很普遍,也基本不太会错,但最近用VPN(这套系统用的是网页反代的方式来实现),下载的Excel却无法打开,仔细检查后通过增加ContentType,修正了这个问题。代码分享如下:
byte[] bytes = System.IO.File.ReadAllBytes(path);
ms.Write(bytes, 0, bytes.Length);
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(displayFileName));
string contentType = GetContentType(path);
if (!string.IsNullOrEmpty(contentType))
{
Response.ContentType = contentType;
}
Response.BinaryWrite(ms.ToArray());
Response.End();
其中ContentType部分如下:
public const string ExcelContentType_97Or2003 = "application/vnd.ms-excel";
public const string ExcelContentType_2007 = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public string GetContentType(string path)
{
string extension = Path.GetExtension(path).ToLower();
if (extension.EndsWith("xlsx") || extension.EndsWith("xlsm"))
{
return ExcelContentType_2007;
}
else if (extension.EndsWith("xls"))
{
return ExcelContentType_97Or2003;
}
return string.Empty;
}