下载大文件时浏览器崩溃

Browser crashes while downloading large size files

本文关键字:浏览器 崩溃 文件 下载      更新时间:2023-09-26

我有一个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大小的文件。