Menu

Creating a service to save and delete file in Windows Azure Storage Blob

Since Azure websites are created with required disk space to host the file that gets published, if you have any file uploads in your application – there will be no disk space to save them. This could be due to security too. So the option is the use the Windows Azure Blob Storage to save files, you can save any file regardless of the file time, from a simple image to a video.

First, you need to install the NuGet package for Windows Azure Blob Storage called “WindowsAzure.Storage”.

    public class StorageService : IStorageService
    {
        private readonly BlobServiceSettings _blobServiceSettings;

        public StorageService(IOptions<BlobServiceSettings> blobServiceSettings)
        {
            _blobServiceSettings = blobServiceSettings.Value;
        }
        
        public string GetQualifiedUrl(string blobFileName)
        {
            if (!string.IsNullOrWhiteSpace(blobFileName))
                return $"{_blobServiceSettings.StorageUrl}{blobFileName}";

            return blobFileName;
        }
        public async Task<string> SaveAsync(string extension, byte[] image)
        {
            var uniqueFilename = $"{Guid.NewGuid().ToString()}{extension}";
            var blob = GetBlobReference(uniqueFilename);

            await blob.UploadFromByteArrayAsync(image, 0, image.Length);
            return uniqueFilename;
        }

        public async Task DeleteAsync(string filename)
        {
            var blob = GetBlobReference(filename);
            await blob.DeleteIfExistsAsync();
        }

        private CloudBlockBlob GetBlobReference(string filename)
        {
            var url = string.Concat(_blobServiceSettings.StorageUrl, filename);
            var creds = new StorageCredentials(_blobServiceSettings.AccountName, _blobServiceSettings.AccountKey);
            return new CloudBlockBlob(new Uri(url), creds);
        }
    }

 

 

Leave a comment