關於Reponse.Flush()的使用

來源:互聯網
上載者:User

Web項目中需要把伺服器上的一個檔案下載到用戶端。代碼很簡單,直接貼上代碼

        /// <summary>
        ///  下載查看檔案方法
        /// </summary>
        /// <param name="fileserverURL">檔案的相對路徑(上傳到伺服器中的虛擬路徑)。如:E:\User\\aa\\a.doc</param>
        /// <param name="page">所操作的頁面名稱</param>
        /// <returns>下載檔案成功返回true,否則返回flase</returns>
        public bool FilesDownload(string fileserverURL, System.Web.UI.Page page)
        {
            try
            {
                string fileserverpath = page.Server.MapPath(fileserverURL);
                System.IO.FileInfo fi = new System.IO.FileInfo(fileserverpath);
                fi.Attributes = System.IO.FileAttributes.Normal;
                System.IO.FileStream filestream = new System.IO.FileStream(fileserverpath, System.IO.FileMode.Open);
                long filesize = filestream.Length;
                int i = Convert.ToInt32(filesize);

                page.Response.ContentType = "application/octet-stream";
                page.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(fileserverpath, System.Text.Encoding.UTF8));
                page.Response.AddHeader("Content-Length", filesize.ToString());
                byte[] fileBuffer = new byte[i];
                filestream.Read(fileBuffer, 0, i);
                filestream.Close();
                page.Response.BinaryWrite(fileBuffer);
                page.Response.Buffer = true;
                page.Response.Flush();
                //page.Response.Clear();
                page.Response.Close();
                page.Response.End();
                return true;
            }
            catch
            {
                return false;
            }
        }

在使用page.Response.Flush()前,需要加上page.Response.Buffer=true這句;表示對輸出的內容進行緩衝,執行page.Response.Flush()時,會等所有內容緩衝完畢,將內容發送到用戶端。這樣就不會出錯,造成頁面卡死狀態,讓使用者無限制的等下去。page.Response.Buffer = true和page.Response.Flush()常一起使用。不然page.Response.Flush()會報錯。另外page.Response.Clear()這句注釋掉了,表示不會清除緩衝區裡的內容,使用者多次在同一個頁面下載檔案時,就直接從緩衝中讀取檔案,下載到用戶端,去掉這句,當第二次,第三次請求檔案時,頁面呈卡死狀態。

 

聯繫我們

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