/// <summary>
/// 文件下载类
/// 调用1:DownLoadFile("/2003.xls", null);
/// 调用2:DownLoadFile("/2003.xls", "");
/// 调用3:DownLoadFile("/2003.xls", "temp.xls");
/// </summary>
/// <param name="URL">文件路径(格式:/upload/2003.xls)</param>
/// <param name="filename">自定义文件名(不想自定义文件名请传[ "" or null ] )</param>
public void DownLoadFile(string URL, string filename)
{
string filePath = System.Web.HttpContext.Current.Server.MapPath("./") + URL;//路径
if (string.IsNullOrEmpty(filename))
filename = System.IO.Path.GetFileName(filePath);
//以字符流的形式下载文件
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename));
System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
作者:达奇
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。