標籤

more tags...

最新回覆

ASP.NET解決網頁下載檔案過大的問題,使用stream方式下載

這個問題很久之前就有人問過了,最近又有人問到,就把它放在我的blog裡

一般下載檔案都會用Response.WriteFile(FullName)

這樣會造成 Aspnet_wp.exe 暫存了太大空間而導致下載失敗,建議採用stream方式下載

asp.net(c#)

部分程式碼

        System.IO.Stream iStream = null;

        //以10K為單位暫存:
        byte[] buffer = new Byte[10000];

        int length;

        long dataToRead;

        // 制定文件路徑.
        string filepath = Server.MapPath("~/aaa.rar");

        //  得到文件名.
        string filename = System.IO.Path.GetFileName(filepath);

        try
        {
            // 打開文件.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);


            // 得到文件大小:
            dataToRead = iStream.Length;

            Response.ContentType = "application/x-rar-compressed";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename));

            while (dataToRead > 0)
            {
                //保証client連接
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10000);

                    Response.OutputStream.Write(buffer, 0, length);

                    Response.Flush();

                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }

                else
                {
                    //结束循環
                    dataToRead = -1;
                }

            }

        }

        catch (Exception ex)
        {
            // error
            Response.Write("Error : " + ex.Message);
        }

        finally
        {
            if (iStream != null)
            {
                //關閉文件
                iStream.Close();
            }

        }

參考網址:

http://www.blueshop.com.tw/board/show.asp?subcde=BRD200706131110357NX&fumcde=

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080506151701ZMH&fumcde=FUM20041006161839LRJ

推到 Twitter!
推到 Plurk!


 

2008/5/6 15:45| 閱讀數 : 4499 | 2 人收藏 1 人推薦 我要推薦 | 2 Comments | 文章分類 : ASP.NET 訂閱


回覆

# re: ASP.NET解決網頁下載檔案過大的問題,使用stream方式下載, Posted by unicorn on 2008/5/8 上午 03:02  回覆

也可以用 Response.TransmitFile

# re: ASP.NET解決網頁下載檔案過大的問題,使用stream方式下載, Posted by puma on 2008/10/15 上午 09:32  回覆

更多Response.TransmitFile的參考資料...

http://weblogs.asp.net/dmiyamasu/archive/2008/02/25/save-server-memory-with-response-transmitfile.aspx

http://forums.asp.net/t/1185493.aspx

發表回覆

標題: *
姓名: *
Email: (將不會被顯示)
Url:
回覆: *
登入後使用進階評論
Please add 3 and 7 and type the answer here:
F6 Team logo


用BloggerAds 替自已加薪

每月文章

文章分類

推薦討論區

推薦部落格