using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Hutopy.Application.Common.Interfaces;
using Microsoft.Extensions.Configuration;
namespace Hutopy.Infrastructure.AzureBlob;
public class AzureBlobStorageService : IAzureBlobStorageService
{
private readonly BlobServiceClient _blobServiceClient;
public AzureBlobStorageService(IConfiguration configuration)
{
var connectionString = configuration["Azure-Blob-Connection-String"] ?? "";
_blobServiceClient = new BlobServiceClient(connectionString);
}
///
/// Upload a file to microsoft azure blob storage.
///
/// The blob name (path within the container, include the file name).
/// The name of the container where the file is stored.
/// The stream.
///
public async Task UploadFileAsync(string containerName, string blobName, Stream fileStream)
{
// Get a reference to a container
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
// Create the container if it does not exist
await containerClient.CreateIfNotExistsAsync();
// Get a reference to a blob
var blobClient = containerClient.GetBlobClient(blobName);
// Upload the file
await blobClient.UploadAsync(fileStream, true);
// Return the URI of the uploaded blob
return blobClient.Uri.ToString();
}
///
/// Download a file to microsoft azure blob storage.
///
/// The blob name (path within the container).
/// The name of the container where the file is stored. (users)
///
public async Task DownloadFileAsync(string containerName, string blobName)
{
// Get a reference to a container
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
// Get a reference to a blob
var blobClient = containerClient.GetBlobClient(blobName);
try
{
// Download the blob to a stream
BlobDownloadInfo download = await blobClient.DownloadAsync();
MemoryStream memoryStream = new();
await download.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0; // Ensure the stream is at the beginning
return memoryStream;
}
catch (Exception ex)
{
// Log and handle the exception as needed
throw new ApplicationException("Error downloading file from Azure Blob Storage.", ex);
}
}
}