如何使用更少的内存从 Azure 存储帐户 return 文件?

How to return file from Azure Storage Account using less memory?

我的代码需要帮助。问题是我的代码在 return 将其发送给用户之前从内存中的 Azure 存储帐户加载了整个文件我想要 return 文件而不消耗大量内存。文件大小从 5MB 到几 GB 不等,但当文件很大时,所有内存都会被消耗,应用服务会崩溃。

    public async Task<IActionResult> GetFile(string blobName)
    {
        CloudBlockBlob blockBlob;


        await using (MemoryStream memoryStream = new MemoryStream())
        {
            string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
            string blobContainer = _configuration.GetValue<string>("blobcontainer");

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);
            blockBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
            await blockBlob.DownloadToStreamAsync(memoryStream);
        }

        Stream blobStream = blockBlob.OpenReadAsync().Result;
        return File(blobStream, blockBlob.Properties.ContentType, blockBlob.Name.Remove(0,9));

    }

我将解决方案总结如下。

当我们使用较少的内存从 Azure 存储下载 blob 的内容时,请使用方法 OpenReadAsync。它将 return 一个可读流然后我们可以直接读取流中的 blob 内容。所以我们不需要提供MemoryStream来保存内容。详情请参考document