/// <summary>
/// 下载文件
/// </summary>
/// <param name="vPath">文件路径(绝对路径)</param>
public static void DownloadData(string path)
{
if (File.Exists(path))
{
FileInfo DownloadFile = new FileInfo(path);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
else
{
throw new Exception("提示:下载失败,找不到该文件");
}
}
/// 下载文件
/// </summary>
/// <param name="vPath">文件路径(绝对路径)</param>
public static void DownloadData(string path)
{
if (File.Exists(path))
{
FileInfo DownloadFile = new FileInfo(path);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
else
{
throw new Exception("提示:下载失败,找不到该文件");
}
}
本文介绍了一种使用C#实现文件下载的方法。通过检查文件是否存在并设置HTTP响应头来触发浏览器下载行为。此方法适用于服务器端文件提供场景。
3万+

被折叠的 条评论
为什么被折叠?



