使用适用于 .NET 的 Azure Blob 存储客户端库 v12 下载 blob

Download blob using Azure Blob storage client library v12 for .NET

我正在使用 Azure.Storage.Blobs 版本=12.4.1。 我有一个 REST 端点,我想用它从存储帐户下载 blob。

我需要将结果流式传输到 HttpResponseMessage,我不想使用 MemoryStream。我想将结果直接流式传输到调用客户端。有没有办法实现这一目标。 HttpResponseMessage内容中如何获取下载的blob?我不想使用 MemoryStream,因为会有很多下载请求。

BlobClient class 有一个方法 DownloadToAsync 但它需要一个 Stream 作为参数。

        var result = new HttpResponseMessage(HttpStatusCode.OK);

        var blobClient = container.GetBlobClient(blobPath);
        if (await blobClient.ExistsAsync())
        {
            var blobProperties = await blobClient.GetPropertiesAsync();

            var fileFromStorage = new BlobResponse()
            {                    
                ContentType = blobProperties.Value.ContentType,
                ContentMd5 = blobProperties.Value.ContentHash.ToString(),
                Status = Status.Ok,
                StatusText = "File retrieved from blob"
            };

            await blobClient.DownloadToAsync(/*what to put here*/);
            return fileFromStorage;
        }

尝试使用下面的代码将 blob 下载到 HttpResponseMessage 中。

try
{
    var storageAccount = CloudStorageAccount.Parse("{connection string}");
    var blobClient = storageAccount.CreateCloudBlobClient();
    var Blob = await blobClient.GetBlobReferenceFromServerAsync(new Uri("https://{storageaccount}.blob.core.windows.net/{mycontainer}/{blobname.txt}"));
    var isExist = await Blob.ExistsAsync();
    if (!isExist) {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "file not found");
    }
    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
    Stream blobStream = await Blob.OpenReadAsync();
    message.Content = new StreamContent(blobStream);
    message.Content.Headers.ContentLength = Blob.Properties.Length;
    message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(Blob.Properties.ContentType);
    message.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "{blobname.txt}",
        Size = Blob.Properties.Length
    };
    return message;
}
catch (Exception ex)
{
    return new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.InternalServerError,
        Content = new StringContent(ex.Message)
    };
}

您可以简单地创建一个新的内存流并将 blob 的内容下载到该流。

类似于:

        var connectionString = "UseDevelopmentStorage=true";
        var blobClient = new BlockBlobClient(connectionString, "test", "test.txt");
        var ms = new MemoryStream();
        await blobClient.DownloadToAsync(ms);

ms 将包含 blob 的内容。不要忘记在使用之前将内存流的位置重置为 0

您需要使用

 BlobDownloadInfo download = await blobClient.DownloadAsync();

download.Content 是 blob 流。您可以使用它直接复制到其他流。

using (var fileStream = File.OpenWrite(@"C:\data\blob.bin"))
{
    await download.CopyToAsync(fileStream);
}

要使用 Azure.Storage.Blobs v12.11.0 下载 blob,我们可以使用 OpenReadAsync or OpenRead

string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING")!;
var serviceClient = new BlobServiceClient(connectionString);
var container = serviceClient.GetBlobContainerClient("myblobcontainername");

string blobName; // the name of the blob
var client = container.GetBlobClient(HttpUtility.UrlDecode(blobName));
var properties = (await client.GetPropertiesAsync()).Value;
Response.Headers.Add("Content-Disposition", $"attachment; filename={Path.GetFileName(client.Name)}");
Response.Headers.Add("Content-Length", $"{properties.ContentLength}");
return File(await client.OpenReadAsync(), properties.ContentType);