Download File from Blob Storage .net core Azure Function C#
Asked Answered
L

0

8

Note: This is a share. Couple days ago I tried to use Azure Function to build an API manipulating "blob storage operations CRUD", I having investigated a solution to solve the download operation, since the majority internet solutions I found work it locally but while deploy my function the Web server needs the grant permission path to Create File and download locally which generated the error:"Access to path is denied". Then I Solved download via HTTP response whit Azure function V2, C# .net core 2.1 This is the basic code it works me, I hope it helps you...

using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;

namespace BloApi
{
    public static class BlobOperations
    {
        [FunctionName("DownloadBlob")]
        public static async Task<HttpResponseMessage> DownloadBlob(
          [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "DownloadBlob/{name}")] HttpRequest req, string name)
        {
            StorageCredentials storageCredentials = new StorageCredentials("Storage",
                "CamEKgqVaylmQ.....ow2VHlyCww==");
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
            CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("MyBlobContainer");
            var blobName = name;
            CloudBlockBlob block = container.GetBlockBlobReference(blobName);
            HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
            Stream blobStream = await block.OpenReadAsync();
            message.Content = new StreamContent(blobStream);
            message.Content.Headers.ContentLength = block.Properties.Length;
            message.StatusCode = HttpStatusCode.OK;
            message.Content.Headers.ContentType = new MediaTypeHeaderValue(block.Properties.ContentType);
            message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = $"CopyOf_{block.Name}",
                Size = block.Properties.Length
            };
            return message;
        }
    }
}
Landlubber answered 23/11, 2019 at 21:3 Comment(3)
So this is not a question, it's a share?Enfranchise
Sorry, yes it is, You right!!Landlubber
Any equivalent in nodejs ?Retouch

© 2022 - 2024 — McMap. All rights reserved.