1、该方法传入的参数为需要下载的文件(需要包含绝对路径)
/// <summary>
/// 通过文件流下载文件
/// </summary>
/// <param name="url">文件名称(包含目录和后缀名)</param>
private void DownLoadPic(string url)
{
string sFileName = url ;
FileStream fileStream = new FileStream(sFileName, FileMode.Open);
long fileSize = fileStream.Length;
byte[] fileBuffer = new byte[fileSize];
fileStream.Read(fileBuffer, 0, (int)fileSize);
//如果不写fileStream.Close()语句,用户在下载过程中选择取消,将不能再次下载
fileStream.Close();
Context.Response.ContentType = "application/octet-stream";
Context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(这里是你想要下载文件的文件名), Encoding.UTF8));
Context.Response.AddHeader("Content-Length", fileSize.ToString());
Context.Response.BinaryWrite(fileBuffer);
Context.Response.End();
Context.Response.Close();
}
2、下载指定路径的文件
/// <summary>
/// 文件流方式下载附件
/// </summary>
/// <param name="path">包含文件名的相对路径</param>
/// <param name="name">下载后的新文件名</param>
public static void DownloadFile(string path, string name)
{
if (!string.IsNullOrEmpty(path))
{
string filePath = HttpContext.Current.Server.MapPath(path);
FileInfo fileInfo = new FileInfo(filePath);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(name)));
HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(fileInfo.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}