簡體   English   中英

在 ASP.NET 中將大文件寫入 HttpResponse 的最有效方法

[英]Most efficient way to write large files to HttpResponse in ASP.NET

我正在創建一個 ZIP 文件。 我正在使用dotnetzip來執行此操作。 我的 ZIP 文件的大小可以 go 高達 500 MB,許多用戶試圖同時下載它。

提供文件的最有效方式是什么? 如果可以選擇,我也不希望將文件保存在磁盤上,因為可能會導致嚴重的磁盤空間限制。

編輯:關於我的用例的更多信息:

我們將文件托管在 SharePoint 2010 資產庫中,該資產庫托管在擁有世界各地用戶的 Intranet 站點中。 這些文件的大小通常為 10-80 MB。 用戶希望能夠一次下載多個文件。

好吧,理論上

對於傳統的 ASP.Net 應用程序,您應該能夠將響應數據(字節)寫入HttpContext.Response.OutputStream (如何獲得 http 響應上下文將取決於您如何處理下載請求,例如,如果您正在實現IHttpHandler然后你得到 http 上下文傳遞給你)。

查看 DotNetZip 示例,看起來Save方法采用 stream,所以這很簡單

zip.Save(context.Response.OutputStream);

If the zip file is re-used and downloaded by many users then you can instead write the zip to a MemoryStream when creating the zip which allows you to later copy the contents of this memory stream to individual responses:

MemoryStream stream = new MemoryStream()
zip.Save(stream);
// Save data somewhere common (e.g. cache it)
byte[] data = stream.ToArray();

將此數據寫回響應:

MemoryStream reader = new MemoryStream(data);
CopyStream(reader, context.Response.OutputStream);

有關 CopyStream 的實現,請參閱在兩個 Stream 實例之間復制的最佳方式 - C#。

然而在現實中

想一想,這意味着如果 zip 文件為 500MB,我們將在 memory 中存儲 500MB 數據 - 如果這是唯一的 ZADCDBD79A8D84175C229B192AADC02很快就會耗盡“內存”(即虛擬地址空間)。

解決方案? 恐怕最簡單的方法是將您的 zip 保存到文件中(即使它是 IIS 不直接提供的臨時文件)而不是 memory stream:

// To save the zip
string filename = Path.GetTempFileName();
zip.Save(filename);

// To write the file
context.Response.TransmitFile(filename);

完成后,您可能還應該刪除該文件。

Note that you only need to bother with this if you are determined to share the same zip between multiple users - if you just construct the zip on a per-user basis and write it directly to the output stream using zip.Save(OutputStream) then事情少了很多麻煩。 我的建議是首先以簡單的方式進行操作,然后測試您是否遇到性能問題,而這些問題只需創建一次 zip 即可解決。

為此,您可能會通過使用消息隊列異步執行它來做得更好。 這樣,壓縮被添加到隊列中,您可以讓一台服務器或多台服務器來執行此操作。 我不知道這是否符合您的要求。

我以前使用過 Rabbit MQ (http://www.rabbitmq.com/)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM