c# - How to download a file to browser from Azure Blob Storage

C# - How to download a file to browser from Azure Blob Storage

In C#, you can download a file from Azure Blob Storage and send it to a web browser in an ASP.NET application (such as ASP.NET Core or ASP.NET MVC). This involves retrieving the blob from Azure Blob Storage and then returning it as a file to the browser.

Prerequisites

To interact with Azure Blob Storage, you need the Azure.Storage.Blobs package. Ensure it's installed in your project via NuGet:

dotnet add package Azure.Storage.Blobs 

Setting Up Azure Blob Storage

To connect to Azure Blob Storage, you need the connection string or a Shared Access Signature (SAS) URL, and details about the container and blob.

Controller to Download a File

In an ASP.NET Core controller, you can create an endpoint to download a file from Azure Blob Storage and send it to the browser. The key is to fetch the blob from Azure, then return it as a FileStreamResult or FileContentResult with appropriate headers.

Here's an example of a simple controller that downloads a file from Azure Blob Storage and sends it to the browser:

using Azure.Storage.Blobs; using Microsoft.AspNetCore.Mvc; using System.IO; using System.Threading.Tasks; public class FileDownloadController : Controller { private readonly string connectionString = "Your_Azure_Storage_Connection_String"; private readonly string containerName = "YourContainerName"; // Download a specific blob from the Azure container public async Task<IActionResult> DownloadFile(string blobName) { // Create a BlobServiceClient to interact with Azure Blob Storage BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); // Get a reference to the specified container BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName); // Get a reference to the specified blob BlobClient blobClient = containerClient.GetBlobClient(blobName); // Download the blob content BlobDownloadInfo downloadInfo = await blobClient.DownloadAsync(); // Return the content as a file to the browser return File( downloadInfo.Content, // Content stream from Azure Blob Storage downloadInfo.ContentType, // MIME type of the blob blobName // The suggested file name for the browser ); } } 

Explanation

  • The BlobServiceClient connects to Azure Blob Storage using a connection string.
  • The BlobContainerClient is used to get a reference to the specific container.
  • The BlobClient gets a reference to the specific blob by its name.
  • BlobDownloadInfo is obtained using DownloadAsync, providing the content stream.
  • The File method creates a FileStreamResult or FileContentResult with the appropriate content type and suggested file name.
  • ContentType should be determined from the blob metadata or set manually based on known file types. Default to application/octet-stream if unknown.

Additional Considerations

  • Authorization and Security: Ensure you have proper authorization to access Azure Blob Storage. Consider using Azure Active Directory authentication for enhanced security.
  • Exception Handling: Handle exceptions like BlobNotFoundException for cases when the blob doesn't exist or network issues occur.
  • File Size: Consider the impact of large file downloads on server resources. Use streaming to manage memory efficiently.
  • CORS Policy: If you're accessing this endpoint from a different domain (e.g., an AJAX call), ensure you have a CORS policy that allows cross-origin requests.

With these steps, you can create an endpoint in ASP.NET Core that retrieves a file from Azure Blob Storage and sends it to a browser for download.

Examples

  1. Download File from Azure Blob Storage to Browser in ASP.NET MVC

    • Description: Use CloudBlockBlob to get a file from Azure Blob Storage and download it to the browser in ASP.NET MVC.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System.Web.Mvc; public class FileDownloadController : Controller { public ActionResult DownloadFile(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var blobStream = blob.OpenRead(); // Return a FileResult to download the file to the browser return File(blobStream, "application/octet-stream", blobName); } } 
  2. Download File from Azure Blob Storage with Presigned URL in ASP.NET

    • Description: Generate a presigned URL for a blob, allowing direct download from Azure Blob Storage.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System; public class PresignedUrlGenerator { public string GetPresignedUrl(string blobName, int expirationMinutes = 10) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(expirationMinutes) }); return blob.Uri + sasToken; } } 
  3. Download File from Azure Blob Storage in ASP.NET Core

    • Description: Download a file from Azure Blob Storage to the browser in an ASP.NET Core application.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.AspNetCore.Mvc; using System.IO; public class FileDownloadController : Controller { [HttpGet("download/{blobName}")] public IActionResult DownloadFile(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); MemoryStream memoryStream = new MemoryStream(); blob.DownloadToStream(memoryStream); memoryStream.Position = 0; // Reset stream position for download return File(memoryStream, "application/octet-stream", blobName); } } 
  4. Download File from Azure Blob Storage to Browser with Specific MIME Type in C#

    • Description: Download a file from Azure Blob Storage to the browser with a specific MIME type.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System.Web.Mvc; public class FileDownloadController : Controller { public ActionResult DownloadFileWithMimeType(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var blobStream = blob.OpenRead(); string mimeType = blob.Properties.ContentType; // Get the MIME type from the blob properties return File(blobStream, mimeType, blobName); } } 
  5. Download Large File from Azure Blob Storage in ASP.NET MVC

    • Description: Handle downloading large files from Azure Blob Storage in ASP.NET MVC to avoid memory issues.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System.Web.Mvc; public class FileDownloadController : Controller { public ActionResult DownloadLargeFile(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var blobStream = blob.OpenRead(); // Ensure that the response is not cached, preventing large files from causing memory issues Response.Buffer = false; Response.BufferOutput = false; return File(blobStream, "application/octet-stream", blobName); } } 
  6. Download File from Azure Blob Storage with Download Progress in C#

    • Description: Implement download progress indication when downloading a file from Azure Blob Storage.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System; using System.Web.Mvc; public class FileDownloadController : Controller { public ActionResult DownloadFileWithProgress(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var blobStream = blob.OpenRead(); blob.DownloadProgress += (sender, e) => { Console.WriteLine($"Download progress: {e.BytesTransferred} bytes transferred."); }; return File(blobStream, "application/octet-stream", blobName); } } 
  7. Download File from Azure Blob Storage in Web API with C#

    • Description: Use a Web API to download a file from Azure Blob Storage to the browser.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.AspNetCore.Mvc; using System.IO; [ApiController] [Route("[controller]")] public class FileDownloadController : ControllerBase { [HttpGet("download/{blobName}")] public IActionResult DownloadFile(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); MemoryStream memoryStream = new MemoryStream(); blob.DownloadToStream(memoryStream); memoryStream.Position = 0; return File(memoryStream, "application/octet-stream", blobName); } } 
  8. Download File from Azure Blob Storage in Blazor with C#

    • Description: Handle downloading files from Azure Blob Storage in a Blazor application.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.AspNetCore.Components; using System.IO; using System.Threading.Tasks; public partial class FileDownloader : ComponentBase { private string storageConnectionString = "your-storage-connection-string"; public async Task DownloadFile(string blobName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); MemoryStream memoryStream = new MemoryStream(); await blob.DownloadToStreamAsync(memoryStream); memoryStream.Position = 0; using (var fileStream = new FileStream(blobName, FileMode.Create, FileAccess.Write)) { memoryStream.CopyTo(fileStream); } } } 
  9. Download File from Azure Blob Storage with Content-Disposition in C#

    • Description: Ensure the file is downloaded with a specified name using the Content-Disposition header.
    • Code:
      using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System.Web.Mvc; public class FileDownloadController : Controller { public ActionResult DownloadFileWithContentDisposition(string blobName) { string storageConnectionString = "your-storage-connection-string"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("your-container-name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); var blobStream = blob.OpenRead(); Response.AddHeader("Content-Disposition", $"attachment; filename=\"{blobName}\""); return File(blobStream, "application/octet-stream", blobName); } } 
  10. Download File from Azure Blob Storage with Client-Server Handshake in C#


More Tags

google-picker jenkins-groovy chartjs-2.6.0 unmarshalling installshield margin picker higher-order-components iasyncenumerable aws-java-sdk

More Programming Questions

More Math Calculators

More Housing Building Calculators

More Animal pregnancy Calculators

More Financial Calculators