///<summary>
/// Web下载文件
///</summary>
///<param name="physicalPath">要下载文件的物理路径</param>
///<param name="contentType">文件类型,如 excel是 application/vnd.ms-excel word 是application/msword</param>
public static void DownloadFile(string physicalPath, string contentType)
{
HttpContext.Current.Response.Clear();
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
string filename = Path.GetFileName(physicalPath);
using (Stream iStream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Length", iStream.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
//HttpContext.Current.Response.Flush();// 测试服务器无法在发送 HTTP 标头之后追加标头
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
}
今天遇到相同的问题,在IIS里是OK的,只是在IIS EXPRESS里存在,代码:
public class PageTimeModule : IHttpModule { void IHttpModule.Dispose() { } void IHttpModule.Init(HttpApplication context) { context.BeginRequest += OnBeginRequest; context.EndRequest += OnEndRequest; } void OnEndRequest(object sender, EventArgs e) { var endTime = DateTime.Now; var elapsedTime = endTime - _beginTime; var application = sender as HttpApplication; var context = application.Context; context.Response.AddHeader("endTime", endTime.ToString()); context.Response.AddHeader("elapsedTime", elapsedTime.TotalMilliseconds.ToString()); } private DateTime _beginTime; void OnBeginRequest(object sender, EventArgs e) { _beginTime = DateTime.Now; var application = sender as HttpApplication; var context = application.Context; context.Request.Headers.Add("beginTime", _beginTime.Ticks.ToString()); context.Response.AddHeader("beginTime", _beginTime.ToString()); } }