Azure

Upload File to Azure Storage Emulator

The Microsoft Azure Storage Emulator provides functionality to emulates the Azure Blob, Queue, and Table services for local development purposes. You can test your app against the storage services locally without creating an Azure subscription account or incurring any costs. When you’re happy with how your application is working in the emulator, switch to using an Azure subscription account in the cloud.

You can download the Azure Storage Emulator here and Install it on your pc.

Note: Remember you have to run this emulator before you run the project.

Implementation

Step-1: In the NuGet Package Manager, search for and select WindowsAzure.Storage. Select Install.

Step-2: Add HomeController.cs in Controllers folder:

using Microsoft.AspNetCore.Mvc;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace blob_test.Controllers
{
    public class HomeController : Controller
    {
        private readonly string connectionString = "UseDevelopmentStorage=true";
        private readonly string containerName = "mycontainer";
        private CloudStorageAccount _storageAccount;
        private CloudStorageAccount StorageAccount
        {
            get
            {
                if (_storageAccount == null)
                {
                    CloudStorageAccount.TryParse(
                        connectionString, out _storageAccount);
                }
                return _storageAccount;
            }
        }
        
        private CloudBlobContainer _container;

        async private Task<CloudBlobContainer> GetContainerAsync()
        {
            if (_container != null) return _container;

            if (StorageAccount != null)
            {
                CloudBlobClient client = StorageAccount.CreateCloudBlobClient();
                _container = client.GetContainerReference(containerName);

                if (!await _container.ExistsAsync())
                    await _container.CreateAsync();
            }

            return _container;
        }

        async public Task<string> GetReadUrlAsync(string blobId, int hours = 0)
        {
            CloudBlobContainer container = await GetContainerAsync();
            if (container == null) return null;

            CloudBlockBlob blob = container.GetBlockBlobReference(blobId);

            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

            sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5);

            if (hours > 0)
                sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(hours);
            else
                sasConstraints.SharedAccessExpiryTime = DateTime.MaxValue.ToUniversalTime();

            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            string url = blob.Uri + sasBlobToken;

            return url;
        }

        async public Task<string> UploadFromFileAsync(string filePath, string contentType)
        {
            CloudBlobContainer container = await GetContainerAsync();
            if (container == null) return null;

            string guid = Guid.NewGuid().ToString();

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(guid);
            blockBlob.Properties.ContentType = contentType;

            using (var fileStream = System.IO.File.OpenRead(filePath))
                await blockBlob.UploadFromStreamAsync(fileStream);


            return guid;
        }

        // Upload file and get URL of the file from Azure storage
        public async Task<string> Index()
        {
            var responseGuid = await UploadFromFileAsync("D://Download.jpg", "image/png"); //Give the File here with File Type
            var fileURL = await GetReadUrlAsync(responseGuid);
            return fileURL;
        }

        // Get all the uploaded file URLs from Azure storage
        public async Task<List<string>> GetListImages()
        {
            CloudBlobContainer container = await GetContainerAsync();
            var response = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.None, 500, null, null, null);

            List<string> imageList = new List<string>();
            foreach (var item in response.Results)
            {
                string url = await GetReadUrlAsync(item.Uri.Segments.Last());
                imageList.Add(url);
            }

            return imageList;
        }

    }
}

So, now our code is ready to perform Upload and Fetch files operation from the Azure local Storage Emulator.

Usage

  • Call the Index() method to upload the file get the URL of the uploaded file.
  • Call the GetListImages() method to fetch all the uploaded file URLs.

 

Let me know in the comments if you face any difficulties.

Thank you.

Ghanshyam Godhani

Experienced Full Stack Software Engineer with a demonstrated history of working in the computer software industry.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago