78 lines
2.8 KiB
C#
78 lines
2.8 KiB
C#
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);
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// Upload a file to microsoft azure blob storage.
|
|
/// </summary>
|
|
/// <param name="blobName">The blob name (path within the container, include the file name).</param>
|
|
/// <param name="containerName">The name of the container where the file is stored.</param>
|
|
/// <param name="fileStream">The stream.</param>
|
|
/// <returns></returns>
|
|
public async Task<string> 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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Download a file to microsoft azure blob storage.
|
|
/// </summary>
|
|
/// <param name="blobName">The blob name (path within the container).</param>
|
|
/// <param name="containerName">The name of the container where the file is stored. (users)</param>
|
|
/// <returns></returns>
|
|
public async Task<MemoryStream> 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);
|
|
}
|
|
}
|
|
}
|