DomBurf
DomBurf

Reputation: 2522

Download a file from Azure blob storage

I am writing a service that uploads / downloads files to and from Azure blob storage. I have the upload part working fine. I've been reading how to download the files and there seems to be several ways of doing it.

I've managed to download the file as a stream which works fine but I read somewhere that it's possible to simply pass the absolute URI of the file and get the browser to download the file.

I'm not sure how to do this. Do I send the URI to the request output stream? Any advice or examples of doing this appreciated. I'm using C# but we have other clients usng this service (such as Angular).

Upvotes: 1

Views: 5951

Answers (2)

Atir Tahir
Atir Tahir

Reputation: 11

Downloading the source file:

public static Stream DownloadFile(string blobName)
{
    CloudBlobContainer container = GetContainer();
    CloudBlob blob = container.GetBlobReference(blobName);
    MemoryStream memoryStream = new MemoryStream();
    blob.DownloadToStream(memoryStream);
    memoryStream.Position = 0;
    return memoryStream;
}

Setting up and returning container:

private static CloudBlobContainer GetContainer()
{
    string accountName = "***";
    string accountKey = "***";
    string endpoint = $"https://{accountName}.blob.core.windows.net/";
    string containerName = "***";
    StorageCredentials storageCredentials = new StorageCredentials(accountName, accountKey);
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(
    storageCredentials, new Uri(endpoint), null, null, null);
    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = cloudBlobClient.GetContainerReference(containerName);
    container.CreateIfNotExists();
    return container;
}

Upvotes: 0

WueF
WueF

Reputation: 460

You need to create endpoint (GET) to obtain public URL as described in Azure Docs and either:

  1. Return it to client who then can invoke GET on returned URI
  2. Return HTTP REDIRECT response with redirection to Blob's public Url

Third option, if you just need client to have this file is to pass streams, so create endpoint returning stream, read Blob to memory stream, and return memorystream to client. Then you don't need to mess with authentication and anonymous access.

Upvotes: 3

Related Questions