[英]Browser crashes while downloading large size files
我有一個Web API,可從azure讀取文件並將其下載到字節數組中。 客戶端接收到此字節數組並將其下載為pdf。 這不適用於大文件。 我無法弄清楚如何將字節從Web api發送到客戶端。
以下是僅將字節數組返回給客戶端的Web API代碼:
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
blockBlob.FetchAttributes();
byte[] data = new byte[blockBlob.Properties.Length];
blockBlob.DownloadToByteArray(data, 0);
return report;
客戶端代碼在ajax請求完成時獲取數據,創建超鏈接並設置其下載文件的下載屬性:
var a = document.createElement("a");
a.href = 'data:application/pdf;base64,' + data.$value;;
a.setAttribute("download", filename);
對於1.86 MB的文件,發生了錯誤。
瀏覽器顯示以下消息:顯示網頁時出了點問題。要繼續,請重新加載網頁。
問題很可能是您的服務器在這些大文件上的內存不足。 不要只將整個文件加載到變量中,然后將其作為響應發送出去。 這將導致兩次下載,您的服務器必須從azure存儲器中下載它並將其保留在內存中,然后您的客戶端必須從服務器中下載它。 您可以改為使用流來進行流復制,這樣就不會占用內存。 這是WebApi控制器中的示例。
public async Task<HttpResponseMessage> GetPdf()
{
//normally us a using statement for streams, but if you use one here, the stream will be closed before your client downloads it.
Stream stream;
try
{
//container setup earlier in code
var blockBlob = container.GetBlockBlobReference(fileName);
stream = await blockBlob.OpenReadAsync();
//Set your response as the stream content from Azure Storage
response.Content = new StreamContent(stream);
response.Content.Headers.ContentLength = stream.Length;
//This could change based on your file type
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
}
catch (HttpException ex)
{
//A network error between your server and Azure storage
return this.Request.CreateErrorResponse((HttpStatusCode)ex.GetHttpCode(), ex.Message);
}
catch (StorageException ex)
{
//An Azure storage exception
return this.Request.CreateErrorResponse((HttpStatusCode)ex.RequestInformation.HttpStatusCode, "Error getting the requested file.");
}
catch (Exception ex)
{
//catch all exception...log this, but don't bleed the exception to the client
return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
}
finally
{
stream = null;
}
}
我已經(幾乎完全)使用了這段代碼,並且能夠下載大小超過1GB的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.