昨天做文件下载时,发现图片文件和文本文件总是会在页面里面打开而不是弹出下载对话框,于是在网上找了很久,最终自己写了一个。
public void DownMaxFile(string filePath,string showFileName)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
int bufferSize = 10000, length = 0;
long dataToRead, startBytes = 0;
Stream iStream = null;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
byte[] buffer = new Byte[bufferSize];
string filename = Path.GetFileName(filePath);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
//查看是否是断点续传请求
if (Request.Headers["Range"] != null)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Response.StatusCode = 206;
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
string[] range = Request.Headers["Range"].Split(new char[]
{ '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
iStream = new FileStream(filePath, FileMode.Open,FileAccess.Read, FileShare.Read);
dataToRead = iStream.Length;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
if (startBytes != 0)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, dataToRead - 1, dataToRead));
}
Response.AddHeader("Accept-Ranges", "bytes");
Response.AddHeader("Content-Length", (dataToRead - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(showFileName, System.Text.Encoding.UTF8));
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
while (dataToRead > 0)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (Response.IsClientConnected)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
length = iStream.Read(buffer, 0, bufferSize);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new Byte[bufferSize];
dataToRead = dataToRead - length;
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
dataToRead = -1;
}
}
}
catch (Exception ex)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Response.Write("Error : " + ex.Message);
}
finally
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (iStream != null)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
iStream.Close();
}
Response.Close();//重要
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}