Today in this article, we will see how to upload/download and delete the files in the cloud using Azure blob storage using ASP.Net Core 5.0 Web API.
- Create an Azure storage account and blob container
- Getting the Access keys (Connection string)
- Create a web API Project (.Net 5.0)
- Connect to Azure Storage account
- Upload file to Azure Blob Storage
- Download file from Azure Blob Storage
- Delete Files
Create an Azure storage account and blob container
Open the Azure
portal and choose the
Storage Account under the Azure Services.
Click on the + New button and it will take us to a new page to create a storage account.
After clicking on create a new storage account the first thing we are going to choose is the subscription you have, next create/select resource group after that, we are going to enter the Storage account name as “newfilestorage” next select the location whichever is right for you for this demo, I am going to choose “(US) East US” location. Next, we are selecting Performance options, here we have Standard Storage and Premium storage option we are going to select “Standard ” for this demo. Next comes your account type, we are going to choose “General-purpose v2” and in replication, we are going to choose “Geo-redundant storage (GRS)” and last option access tier we going to choose “Hot storage” at last click on review + create button.
After clicking on the Review + create here we can see the validation passed status and along with the review page with all the options which we had opted for and then click on create a button at the bottom to create a storage account.
Storage account
Create a blob container under the storage account
To store the actual documents or files we need a blob container under the same storage account. Let's create a new blob container. Open the newly created storage account and under the left side options, you will find the named Container click on that where it gives us an option to create a new container.
Provide the name for the new container, choose the access level, and click on the create button at the bottom of the page.
Getting the Access keys (Connection string)
Now here comes the main picture after the creation of the blob container, to incorporate the Azure storage account in the project we need to get the Access keys in communicating our project with our Azure storage account.
Access keys
Created by default when we set up the storage account.
From this screen, we are going to copy the Connection string (key 1).
Create a Web API Project (.Net 5)
Open the Visual Studio and chose the ASP.Net Core Web API and once after that choose the .Net 5.0 template from the dropdown it will create a project under the .Net 5 target framework.
Install the package which will communicate with the Azure Storage account,
Connect to Azure Storage account
Here we are going to add the connection string and as well as blob container name to the appsettings.json file with the key name BlobConnectionString & BlobContainerName and we need to pass the connection string and container name which we have copied from Access Key.
appsettings.json
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*",
- "BlobConnectionString": "*Your Connection string*",
- "BlobContainerName": "*Your container name*"
- }
After adding the keys, Now we are going to create a FileController (API) and injecting the IConfiguration for accessing the keys from the appsettings.json file.
FileController.cs
After creating the controller we are going to add the constructor for it for injecting the Iconfiguration dependency in order to fetch the values,
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- namespace UploadAndDownload_AzureBlobStorage.Controllers {
- [Route("api/[controller]")]
- [ApiController]
- public class FileController: ControllerBase {
- private readonly IConfiguration _configuration;
- public FileController(IConfiguration configuration) {
- _configuration = configuration;
- }
- }
- }
Next, we are going to add a post method where we are going to use UploadFromStreamAsync to upload bytes.
In the Post method, you see the IFormFile interface as input which will get file details that are posted, then the first thing we are going to get is the connection string (“BlobConnectionString“) from the appsettings.json file using IConfiguration.
Next, we are going to retrieve the storage account from the connection string, after that we are going to create a blob client, we are going to use cloudBlobClient to Retrieve a reference to a container.
Then to retrieve posted file information, we are going to use files.OpenReadStream and copy them to a memory stream and then finally we are going to get the byte array of it to pass the UploadFromStreamAsync method.
Upload File [Post]method
- [HttpPost(nameof(UploadFile))]
- public async Task < IActionResult > UploadFile(IFormFile files) {
- string systemFileName = files.FileName;
- string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");
-
- CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
-
- CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
-
- CloudBlobContainer container = blobClient.GetContainerReference(_configuration.GetValue < string > ("BlobContainerName"));
-
- CloudBlockBlob blockBlob = container.GetBlockBlobReference(systemFileName);
- await using(var data = files.OpenReadStream()) {
- await blockBlob.UploadFromStreamAsync(data);
- }
- return Ok("File Uploaded Successfully");
- }
Download File [Post] method
To download the file from the blob container we need to pass the filename as parameter so that the filename will check and get back with the actual file from the container.
- [HttpPost(nameof(DownloadFile))]
- public async Task < IActionResult > DownloadFile(string fileName) {
- CloudBlockBlob blockBlob;
- await using(MemoryStream memoryStream = new MemoryStream()) {
- string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");
- CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
- CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_configuration.GetValue < string > ("BlobContainerName"));
- blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
- await blockBlob.DownloadToStreamAsync(memoryStream);
- }
- Stream blobStream = blockBlob.OpenReadAsync().Result;
- return File(blobStream, blockBlob.Properties.ContentType, blockBlob.Name);
- }
Delete File [Delete] Method
- [HttpDelete(nameof(DeleteFile))]
- public async Task < IActionResult > DeleteFile(string fileName) {
- string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");
- CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
- CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- string strContainerName = _configuration.GetValue < string > ("BlobContainerName");
- CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);
- var blob = cloudBlobContainer.GetBlobReference(fileName);
- await blob.DeleteIfExistsAsync();
- return Ok("File Deleted");
- }
Now let's run the application and upload the file to Azure blob storage through Swagger
Let's see the file get uploaded to the Azure blob container. Open the storage account and click on the container and open the container where we will find all the uploaded files and their related information.
Download File
Delete File
Now let's go back to the blob container and see where the file gets deleted.
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
keep learning....!