asp.net斷點續傳

來源:互聯網
上載者:User

標籤:blog   http   io   os   ar   sp   檔案   資料   div   

using System;    using System.Data;    using System.Configuration;    using System.Collections;    using System.Web;    using System.Web.Security;    using System.Web.UI;    using System.Web.UI.WebControls;    using System.Web.UI.WebControls.WebParts;    using System.Web.UI.HtmlControls;    using System.IO;    public partial class DFile : System.Web.UI.Page    {    protected void Page_Load(object sender, EventArgs e)    {    }    protected void LinBtnDFile_Click(object sender, EventArgs e)    {    // 建立一位元數組    byte[] buffer = new Byte[10240];    // 指定要下載檔案的路徑.    string filePath = @"D:\愛智旮旯.rar";    // 或取檔案名稱包括副檔名    string fileName = Path.GetFileName(filePath);    Stream fileStream = null;    try    {    // 開啟檔案    fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);    Response.Clear();    // 擷取檔案的大小    long fileSize = fileStream.Length;    long sum = 0;    if (Request.Headers["Range"] != null)    {    Response.StatusCode = 206; // 表示返回到用戶端的 HTTP 輸出狀態的整數。預設值為 200。    sum = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));    }    if (sum != 0)    {    Response.AddHeader("Content-Range", "bytes " + sum.ToString() + "-" + ((long)(fileSize)).ToString() + "/" + fileSize.ToString());    }    // 擷取部分http頭資訊    Response.AddHeader("Content-Length", ((long)(fileSize - sum)).ToString());    Response.ContentType = "application/octet-stream";    //擷取檔案來源    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(fileName)));    // Response.Flush();    fileStream.Position = sum; //設定當前流位置    fileSize = fileSize - sum;    // 當檔案大小大於0是進入迴圈    while (fileSize > 0)    {    // 判斷用戶端是否仍串連在伺服器    if (Response.IsClientConnected)    {    // 擷取緩衝區中的總位元組數.    int length = fileStream.Read(buffer, 0, 10240);    // 寫入資料    Response.OutputStream.Write(buffer, 0, length);    // 將緩衝區的輸出發送到用戶端    Response.Flush();    buffer = new Byte[10240];    fileSize = fileSize - length;    }    else    {    //當使用者斷開後退出迴圈    fileSize = -1;    }    }    }    catch (Exception ex)    {    Response.Write("Error : " + ex.Message);    }    finally    {    if (fileStream != null)    {    //關閉檔案    fileStream.Close();    }    Response.End();    }    }    }

  

asp.net斷點續傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.