gpt4 book ai didi

javascript - 下载大文件时浏览器崩溃

转载 作者:行者123 更新时间:2023-12-03 09:48:30 25 4
gpt4 key购买 nike

我有一个 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 的文件发生错误。

浏览器显示消息:显示网页时出现问题。要继续,请重新加载网页。

最佳答案

问题很可能是您的服务器在处理这些大文件时内存不足。不要将整个文件加载到变量中然后将其作为响应发送出去。这会导致双重下载,您的服务器必须从天蓝色存储下载它并将其保存在内存中,然后您的客户端必须从服务器下载它。您可以进行流到流复制,这样内存就不会被占用。以下是来自 WebApi Controller 的示例。

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 - 下载大文件时浏览器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com