收藏:ASP.NET提供檔案下載函數(支援大檔案、續傳、速度限制、資源佔用小)

來源:互聯網
上載者:User

收藏:ASP.NET提供檔案下載函數(支援大檔案、續傳、速度限制、資源佔用小) (轉自: Arhrun)

// 輸出硬碟檔案,提供下載
// 輸入參數 _Request: Page.Request對象, _Response: Page.Response對象, _fileName: 下載檔案名稱, _fullPath: 帶檔案名稱下載路徑, _speed 每秒允許下載的位元組數
// 返回是否成功
public
static
bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string
_fullPath, long _speed)
{
try
{
FileStream myFile =
new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br =
new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges",
"bytes");
_Response.Buffer =
false;
long fileLength
= myFile.Length;
long startBytes
= 0;

int pack
= 10240;
//10K bytes
//int sleep = 200;
//每秒5次 即5*10K bytes每秒
int sleep
= (int)Math.Floor(1000
* pack
/ _speed) +
1;
if (_Request.Headers["Range"]
!= null)
{
_Response.StatusCode =
206;
string[] range
= _Request.Headers["Range"].Split(new
char[] {'=',
'-'});
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength
- startBytes).ToString());
if (startBytes
!= 0)
{
_Response.AddHeader("Content-Range",
string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1,
fileLength));
}
_Response.AddHeader("Connection",
"Keep-Alive");
_Response.ContentType =
"application/octet-stream";
_Response.AddHeader("Content-Disposition","attachment;filename="
+ HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );

br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount
= (int) Math.Floor((fileLength
- startBytes)
/ pack)
+ 1;

for (int i
= 0; i
< maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i=maxCount;

}
}
}
catch
{
return
false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return
false;
}
return
true;
}

調用例

Page.Response.Clear();

bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:\download.date", 1024000);

if(!success)
Response.Write("下載檔案出錯!");
Page.Response.End();

通過這種方式實現的下載,可控性好,可以控制讀取檔案塊的大小,可以有效實現防盜、可以監控資源的下載等等。如果你能把他封裝的很好的話,這將是一個非常強大的類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.