三、ASP.NET上傳檔案遇到的問題
我們在用ASP.NET上傳大檔案時都遇到過這樣或那樣的問題。設定很大的maxRequestLength值并不能完全解決問題,因為ASP.NET會block直到把整個檔案載入記憶體後,再加以處理。實際上,如果檔案很大的話,我們經常會見到Internet Explorer顯示 "The page cannot be displayed - Cannot find server or DNS Error",好像是怎麼也catch不了這個錯誤。為什麼?因為這是個client side錯誤,server side端的Application_Error是處理不到的。
四、ASP.NET大檔案上傳解決方案
解決的方法是利用隐含的HttpWorkerRequest,用它的GetPreloadedEntityBody 和 ReadEntityBody方法從IIS為ASP.NET建立的pipe裡分塊讀取資料。Chris Hynes為我們提供了這樣的一個方案(用HttpModule),該方案除了允許你上傳大檔案外,還能實時顯示上傳進度。
Lion.Web.UpLoadModule和AspnetUpload 兩個.NET元件都是利用的這個方案。
方案原理:
利用HttpHandler實作了類似于ISAPI Extention的功能,處理請求(Request)的資訊和發送響應(Response)。
方案要點:
1. httpHandler or HttpModule
a.在asp.net程序處理request請求之前截獲request對象
b.分塊讀取和寫入資料
c.實時跟蹤上傳進度更新meta資訊
2. 利用隐含的HttpWorkerRequest用它的GetPreloadedEntityBody 和 ReadEntityBody方法處理檔案流
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;
while (wr.ReadEntityBody(bs2,n) >0)
{
.....
轉載于:https://www.cnblogs.com/lxfgood/archive/2011/05/24/2055808.html