/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="filepath">导出的文件路径</param>
/// <param name="filename"></param>
public static void DownLoadFile(HttpContextBase context, string filepath,string filename)
{
System.IO.FileInfo file = new System.IO.FileInfo(filepath);
context.Response.Clear();
context.Response.Charset = "GB2312";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Server.UrlEncode(filename));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
context.Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
context.Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
context.Response.WriteFile(file.FullName);
//System.IO.File.Delete(path + fileName);//删除临时文件
// 停止页面的执行
context.Response.End();
}
public static void FileDownload(string FilePath, string FileName, string FileType, string FileTitle)
{
string strFullFileName = FilePath + FileName;
long chunkSize = 102400; //建立一个100K的缓冲区
byte[] buffer = new byte[chunkSize];
long dataToRead = 0;//已读的字节数
FileStream stream = null;
stream = new FileStream(strFullFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
if (FileType == "")
{
FileType = FileName.Substring(FileName.LastIndexOf(".") + 1);
}
switch (FileType.ToString().ToUpper())
{
case "XLS":
HttpContext.Current.Response.ContentType = "application/ms-excel";
break;
case "DOC":
HttpContext.Current.Response.ContentType = "application/ms-word";
break;
case "TXT":
HttpContext.Current.Response.ContentType = "application/text";
break;
case "PDF":
HttpContext.Current.Response.ContentType = "application/pdf";
break;
case "GIF":
HttpContext.Current.Response.ContentType = "images/gif";
break;
case "JPG":
HttpContext.Current.Response.ContentType = "images/jpg";
break;
}
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
//HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
dataToRead = -1; //防止client失去连接
}
}
//HttpContext.Current.Response.End();
}
}