Microsoft > Azure >> Cloud Views : 5979
Azure Blob POC
Rate This Article :

Upload document to Azure Blob Storage From .net

Introduction

This article will explain on the steps to create a azure blob storage and upload a simple document to the created blob from a .net core application

High level steps

   1. Creating a Blob storage 
   2. Creating an .net core application to upload the document

Detailed steps Follows

 1.  Creating a Blob Storage

Step 1

Login to Azure portal or create an account in azure and login


Step 2

Search for Storage and select Storage Accounts



Step 3

Click Add + to create a new storage account



Step 4

 Choose the subscription type which you have opted.


Step 5

Resource group: select if you already have created or create a new by clicking the create new link

Below screen is for creating new resource




Step 6

Instance Details



Location: Choose based on the requirement / Physical location /Customer location. Also to consider on features available in that location and compliance


Performance: standard/ Premium, The Standard option offers normal magnetic drives (HDD). They are best for large data and accessed infrequently. Premium offers the SSD which gives the best performance. Standard is Cheaper than Premium


Account kind: StorageV2/Storage/Blob

            StorageV2 (General-purpose v2)

Basic storage account type for blobs, files, queues, and tables. Recommended for most scenarios using Azure Storage

Storage (General-purpose v1)

Legacy account type. Choose the V2 instead of this

Blob

Storage accounts with premium performance characteristics for block blobs and append blobs

For our case we will choose the Blob

 

Replication: LRS/GRS/RA-GRS

Local Redundant storage (LRS):LRS assures your data is replicated 3 times within a single data center– Cheapest option

Geo-redundant storage (GRS): In GRS we get all the features of the LRS storage within your primary zone, but you also get a second LRS data storage in a neighboring Azure region

Read-Access Geo-redundant (RA-GRS): It has all the benefits and redundancy of the standard GRS replication but also allows for the secondary copy stored in the paired sister Azure region to be readable

Blob access tier: Cool/Hot

Choose Hot for frequent data access and cool for infrequently accessed data

 

Step 7

Click review + create and create


Step 8

Once you clicked create it will start deployment and redirect you to deployment complete screen click go to resource to proceed


Step 9

In the Overview screen click the container icon to add a new container


Step 10

Click the + icon to add new container



Give the Name and choose the access level as Blob


The newly created container will be listed inside containers



Step 10

Get the access Key for application connectivity. Click the Access key navigation in the left bar and copy the key 1. Use this as -

connectionString in AsyncUploadFile method in the sample code






 2.Creating a Console app to upload a File and Get URL

Create a Console application(Core application used here)

Add the below nugget package reference




For demonstrating a dynamic File. I have loaded a local file to byte array so that it’s similar to real world scenario.

A pdf File Is placed in the Application folder




Code:

class Program

{

                                static void Main(string[] args)

                                {

 

                                Console.WriteLine("Uploading a File from memory");

                                var filename = GenerateblobFileName("20200918T100727411.pdf");

                                string containerName = "uploadreports";

                                Console.WriteLine(AsyncUploadFile(containerName, GetFileStream(), filename, "application/pdf").Result);

                                Console.Read();

 

                                }

 

                                public static async Task<string> AsyncUploadFile(string containerName,byte[] arr, string filename, string filetype)

                                {

                                                // connection to be given in configuration files or env variable  - Get value from step 10 given in article

                                                var connectionString = "Provide your Azure Blob Connection details";

                                                // create a client with the connection

                                                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

                                                // container name which we created

                                                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

                                                BlobClient blobClient = containerClient.GetBlobClient(filename);

                                                var blobHttpHeader = new BlobHttpHeaders();

                                                blobHttpHeader.ContentType = filetype;

                                                using (MemoryStream ms = new MemoryStream(arr))

                                                {

                                                await blobClient.UploadAsync(ms, blobHttpHeader); // can use memory stream or file stream or Direct File path

                                                }

 

                                                return blobClient.Uri.AbsoluteUri;

                                }

                                // generate a unique name for the files we upload

                                public static string GenerateblobFileName(string fileName)

                                {

                                      string strFileName = string.Empty;

                                      string[] strName = fileName.Split('.');

                                     strFileName = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd") + "/" + DateTime.Now.ToUniversalTime().ToString("yyyyMMdd\\THHmmssfff") + "." +      strName[strName.Length - 1];

                                                return strFileName;

                                }

 

                                //get byte array of a File

                                public static byte[] GetFileStream()

                                {

                                                var basepath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName;

                                                var filepath = basepath + "\\File\\20200918T100727411.pdf";

                                                byte[] fileData = File.ReadAllBytes(filepath);

                                                return fileData;

 

                                }

                                public static  MemoryStream createtextFile()

                                {

                                                using (MemoryStream ms = new MemoryStream())

                                                {

                                                                TextWriter tw = new StreamWriter(ms);

                                                                tw.Write("Azure Blob storage is Microsoft's object storage solution for the cloud..");

                                                                tw.Flush();

                                                                ms.Position = 0;

                                                                return ms;

                                                }

                                }

}

Note : Sample Code Is available as download


           Copy the URL and paste to a browser to see the content 



About Author
ezhilarasan.j
Total Posts 3
-
Comment this article
Name*
Email Address* (Will not be shown on this website.)
Comments*
Enter Image Text*
   
View All Comments
Raji Paul
very nice
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.