這篇文章給大家介紹ASP.NET中如何使用文件下載函數(shù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
大關(guān)ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書(shū)銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書(shū)合作)期待與您的合作!
ASP.NET文件下載函數(shù)使用是什么情況呢?在你的Page_Load中添加這樣的代碼:
Page.Response.Clear(); bool success = ResponseFile(Page.Request, Page.Response, "目的文件名稱", @"源文件路徑", 1024000); if (!success) Response.Write("下載文件出錯(cuò)!"); Page.Response.End();
ASP.NET文件下載函數(shù)代碼為:
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; double 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(int.Parse(pack.ToString()))); Thread.Sleep(sleep); } else { i=maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; }
這樣就實(shí)現(xiàn)了文件下載時(shí),不管是什么格式的文件,都能夠彈出打開(kāi)/保存窗口.
關(guān)于ASP.NET中如何使用文件下載函數(shù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。