用ASP.NET上傳大檔案 載自思歸blogs)

來源:互聯網
上載者:User

我們在上傳大檔案時都遇到過這樣或那樣的問題。設定很大的maxRequestLength值並不能完全解決問題,因為ASP.NET會block直到把整個檔案載入記憶體後,再加以處理。實際上,如果檔案很大的話,我們經常會見到Internet Explorer顯示 "The page cannot be displayed - Cannot find server or DNS Error",好像是怎麼也catch不了這個錯誤。為什嗎?因為這是個client side錯誤,server side端的Application_Error是處理不到的,可以參考這個文章研究一下產生這個錯誤的機理。

handling server error when upload file too large

解決的方法是利用隱含的HttpWorkerRequest,用它的GetPreloadedEntityBody 和 ReadEntityBody方法從IIS為ASP.NET建立的pipe裡分塊讀取資料

  IServiceProvider provider = (IServiceProvider) HttpContext.Current;
  HttpWorkerRequest wr = (HttpWorkerRequest) provider.GetService(typeof(HttpWorkerRequest));
  byte[] bs = wr.GetPreloadedEntityBody();
  ....
  if (!wr.IsEntireEntityBodyIsPreloaded())
  {
        int n = 1024;
        byte[] bs2 = new byte[n];
        while (wr.ReadEntityBody(bs2,n) >0)
       {
             .....
        }
  }

Chris Hynes為我們提供了這樣的一個方案(用HttpModule),該方案除了允許你上傳大檔案外,還能即時顯示上傳進度:

ASP.NET Upload Magic Part 2

這裡有他講座的PPT檔案:

Uploading with ASP.NET (part 1)

Uploading with ASP.NET (part 2)

相關文章

聯繫我們

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