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

时间:2020-05-07 08:39:36

标签: .net azure azure-storage azure-storage-blobs azure-sdk

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

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

BlobClient类具有方法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;
        }

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码将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)
    };
}

答案 1 :(得分:0)

您需要使用

 BlobDownloadInfo download = await blobClient.DownloadAsync();

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

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