下载大文件时浏览器崩溃
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大小的文件。
相关文章:
- 为什么这会造成一个无休止的循环并使我的浏览器崩溃
- javascript audio currentTime使一些浏览器崩溃
- 在浏览器崩溃之前检测到内存耗尽
- 输入输入前浏览器崩溃
- three.js内存泄漏/浏览器崩溃
- Ajax 请求仪表板页面上的浏览器崩溃
- set超时在“while”内会导致浏览器崩溃.我怎样才能避免它
- 设置设置间隔函数正在运行并导致浏览器崩溃
- 高效的Javascript组合函数,不会使浏览器崩溃
- 我的脚本使浏览器崩溃
- SlickGrid在选择大范围的行时使浏览器崩溃
- setInterval 在运行用户脚本时使我的浏览器崩溃
- 添加依赖项后浏览器崩溃
- Javascript/Jquery代码使我的浏览器崩溃
- 无限滚动会导致浏览器崩溃吗?
- 为什么这 while 循环会使浏览器崩溃
- 设置间隔导致浏览器崩溃
- JavaScript函数使我的浏览器崩溃
- 旧的JavaScript函数使浏览器崩溃
- 如何使用 IndexedDB 制作一个很长的字符串而不会使浏览器崩溃