2012年10月14日 星期日

使用 Response 下傳檔案時...讓瀏覽器顯示下載進度

當我們只想要讓有權限的使用者可以下載某些檔案時,通常會寫一支 download.aspx 的程式,由它負責讀取、輸出檔案,這時不要忘了將 "Content-Length" 加到 HTTP Header裡,以告訴瀏覽器將會收到多少資料。

如果你沒加瀏覽器只會顯示目前已下載了多少資料,但無法顯示進度

當加上"Content-Length"後,下載進度就會出現了

Response.AddHeader("Content-Length", iStream.Length.ToString());


private void Download(string filepath)
{
    byte[] buffer = new Byte[10000];
    int length;
    long dataToRead;
    string filename = System.IO.Path.GetFileName(filepath);

    try
    {
        using (var iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read))
        {
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            Response.AddHeader("Content-Length", iStream.Length.ToString());
               
            dataToRead = iStream.Length;
            while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, buffer.Length);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    dataToRead = dataToRead - length;
                }
                else
                {
                    dataToRead = -1;
                }
            }
        }
    }
    catch (Exception ex)
    {
        // Trap the error, if any.
        Response.Write("Error : " + ex.Message);
    }
    finally
    {
        Response.Close();
    }
}



原始文章出自於此




沒有留言:

張貼留言