ASP.NET MVC 以Stream 下載檔案

來源:互聯網
上載者:User

標籤:

 

 

            nl.fileid = Int32.Parse(id);  //伺服器上對應的id            Stream stream = Lawsuit.DownLoad(nl);//伺服器上的Stream 資料            Response.Buffer = false;            Response.AddHeader("Connection", "Keep-Alive");            Response.ContentType = "application/octet-stream";            Response.AddHeader("Content-Disposition", "attachment;filename=" + url); // 此處檔案名稱如果是中文在瀏覽器預設是籌碼,應該加HttpUtility.UrlEncode(filename)   url:為下載檔案的伺服器位址和名稱            while (true)    //如果檔案大於緩衝區,通過while迴圈多次負載檔案             {                //開闢緩衝區空間                   byte[] buffer = new byte[1024];  //讀取檔案的資料                   int leng = stream.Read(buffer, 0, 1024);                if (leng == 0)             //到檔案尾,結束                       break;                if (leng == 1024)            //讀出的檔案資料長度等於緩衝區長度,直接將緩衝區資料寫入                      Response.BinaryWrite(buffer);           //向用戶端發送資料流                 else                {                    //讀出檔案資料比緩衝區小,重新定義緩衝區大小,只用於讀取檔案的最後一個資料區塊                      byte[] b = new byte[leng]; for (int i = 0; i < leng; i++)                        b[i] = buffer[i];                    Response.BinaryWrite(b);                }            }            stream.Close();//關閉下載檔案              Response.End();//結束檔案下載 

 

 

來源地址:http://www.cnblogs.com/chaoa/archive/2012/03/09/2386106.html

ASP.NET MVC 以Stream 下載檔案

聯繫我們

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