Javascript required
Skip to content Skip to sidebar Skip to footer

Upload Files to Azure Blob Storage Asp.net C#

Today, in this article, nosotros will discuss how to develop a web application to store uploaded files into the Azure Hulk Storage. Now, as we all know, Blob Storage is a role of the Azure Storage. And so, beginning, we will discuss some basic concepts nigh Azure Storage so, we will discuss how to store file data into the Azure Blob Storage. The Code example contains the both version of Asp.Net Core i.eastward. two.ane and 3.1.

Definition of Azure Storage

Microsoft provides different ways to shop data or data in Azure. We can use dissimilar database types like Azure SQL Server, Azure Creation DB, or Azure Table Storage. Also, we can use either Azure Queues or Event Hubs for storing and sending a message like an E-mail, SMS, etc. In the same way, we can employ either Azure Files or Azure Hulk Storage to store files in Azure. Normally Azure Storage contains four different data services. These four information services identify together as a group and are named Azure Storage. Azure storage consists of Azure Blobs, Azure Files, Azure Queues, and Azure Tables. These 4 data storage services are always bachelor in special consideration because they all are primitive and cloud-based storage services and can exist used together in the same application. The below paradigm shows all the elements of Azure Storage.

Upload Files In Azure Blob Storage Using ASP.NET Core

Storage Business relationship

In Azure, Storage Business relationship e'er acts as a container that consists of a multiple prepare of Azure Storage Service together. In Storage Account, merely data services from the Azure Storage grouping tin exist included similar Azure Blobs, Files, Queues, and Tables. So, basically, it acts equally a grouping which contains multiple data services of Azure Storage. The beneath image demonstrates the basic concept of Azure Storage Accounts.

Upload Files In Azure Blob Storage Using ASP.NET Core

Prerequisites

  1. Microsoft Visual Studio 2017
  2. Account in Azure Portal.

If yous don't have any existing Azure account, then you tin create a free trial account in the Azure portal using your email id.

Create an Azure Storage Account

To create the Azure Storage Account in Azure Portal, first, you lot demand to log in to the Azure Portal and and so perform the below steps.

Step ane

Click on the Azure Storage Accounts option from the Resources Dashboard.

Upload Files In Azure Blob Storage Using ASP.NET Core

On the Create Azure Storage Account, click on the Add together push on the Storage Business relationship folio.

Upload Files In Azure Blob Storage Using ASP.NET Core

Now, provide the related required information to create an Azure Storage account.

Upload Files In Azure Blob Storage Using ASP.NET Core

Step 4

In the higher up epitome, Storage Account Name means Account Name. Also, select Storage V2 options for availing the service of all four data services of Azure Storage Accounts.

Step 5

At present, click the "Review and Create" button.

Step vi

After the settings are validated, click "Create" to create the business relationship.

Footstep seven

The business relationship cosmos takes some fourth dimension. Wait for the portal to display the notification telling that the deployment succeeded and click the notification.

Step 8

Once the deployment is succeeded, click the "Get to resource" option to open Storage Business relationship.

Step 9

Once Storage Account is created, click on Admission Keys options of the left panel and copy the ConnectionString value. This value is needed to be provided in our web application so that nosotros can upload files in Azure Blob Storage.

Upload Files In Azure Blob Storage Using ASP.NET Core

Create a Spider web Application using ASP.NET Core in Visual Studio

Stride 1

Now, open up Microsoft Visual Studio 2017 and click on File --> New --> Projects.

Upload Files In Azure Blob Storage Using ASP.NET Core

Select the Web Awarding project template and click the OK button.

Upload Files In Azure Blob Storage Using ASP.NET Core

In the Project Template box, select Web Application (Model-View-Controller) options and click on the OK button.

Step 4

At present a blank project solution is ready.

Stride v

Offset, open the App.Config file and shop the connections string to this file which nosotros already copied from the Azure portal.

  1. {
  2. "Logging" : {
  3. "LogLevel" : {
  4. "Default" : "Warning"
  5.     }
  6.   },
  7. "AllowedHosts" : "*" ,
  8. "BlobConnections" : "" ,
  9. "ConnectionStrings" : {
  10. "AccessKey" : "DefaultEndpointsProtocol=https;AccountName=testblobdump;AccountKey=ADSSADS222SSDbfOcGSuHbKnTlExh3kieXy6zwMZ/F3vDnOGT1uV5oy1KEYZ3ui6WFhayHC5tLkCA==;EndpointSuffix=core.windows.net"
  11.   }
  12. }

Stride half dozen

Now, add another Form Library Projection to create the Service Layer.

Step 7

Later adding the new projects, we need to install the below NuGet Packages to access the Azure Storage business relationship using Windows Azure Storage customer driver.

Upload Files In Azure Blob Storage Using ASP.NET Core

Now, add another class library project for Data Context and add together a form called Products and define the Product model class as beneath.

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.ComponentModel.DataAnnotations;
  4. using  Organisation.ComponentModel.DataAnnotations.Schema;
  5. using  Arrangement.Text;
  6. using  Microsoft.AspNetCore.Http;
  7. namespace  DataContext.Models
  8. {
  9.     [Table("Product" , Schema = "Core" )]
  10. public class  Product
  11.     {
  12. public  Product()
  13.         {
  14.             CreatedDate = DateTime.Now;
  15.         }
  16.         [Cardinal]
  17. public int  ProductId { get ; set ; }
  18.         [Required(ErrorMessage ="Please Enter Name" )]
  19.         [Cavalcade(TypeName ="varchar(l)" )]
  20. public string  Name { become ; prepare ; }
  21. public decimal  UnitPrice { go ; gear up ; }
  22.         [Required(ErrorMessage ="Please Enter Description" )]
  23.         [Column(TypeName ="varchar(500)" )]
  24. public cord  Description { get ; fix ; }
  25.         [Column(TypeName ="varchar(fifty)" )]
  26. public string  ImageName { get ; fix ; }
  27.         [Column(TypeName ="varchar(250)" )]
  28. public string  ImagePath { get ; prepare ; }
  29. public  DateTime CreatedDate { get ; set ; }
  30. public  DateTime? UpdatedDate { become ; prepare ; }
  31.         [NotMapped]
  32. public  IFormFile File { get ; set ; }
  33.     }
  34. }

Pace ix

Now, select the Service Layer Projects and Create a New Binder chosen AppConfig.

Step 10

At present, within this folder, add a new class file chosen AppConfiguration.cs where we volition read the configuration file value past providing the primal as beneath.

  1. using  Microsoft.Extensions.Configuration;
  2. using  System;
  3. using  System.Collections.Generic;
  4. using  Organisation.IO;
  5. using  System.Text;
  6. namespace  ServiceLayer.AppConfig
  7. {
  8. public static course  AppConfiguration
  9.     {
  10. private static  IConfiguration currentConfig;
  11. public static void  SetConfig(IConfiguration configuration)
  12.         {
  13.             currentConfig = configuration;
  14.         }
  15. public static string  GetConfiguration( string  configKey)
  16.         {
  17. attempt
  18.             {
  19. cord  connectionString = currentConfig.GetConnectionString(configKey);
  20. render  connectionString;
  21.             }
  22. grab  (Exception ex)
  23.             {
  24. throw  (ex);
  25.             }
  26. return "" ;
  27.         }
  28.     }
  29. }

Step 11

Now, add another class called BlobStorageService.cs and add the below code. This service is basically responsible to shop the uploaded file byte contained in the Azure Blob Storage. When it volition upload the file in blob storage, it first creates a container called Upload and so within the container create a logical folder with the current date, then inside that logical binder original file will be stored. Simply in this example, we need to retrieve ane thing very clearly that in Azure Blob Storage, there is no option for creating a folder. We tin can carve up uploaded files logically in a date-wise, month-wise, or year wise subgrouping. This can be washed with the help of the file proper noun.

For example, suppose we provide a file proper noun like this,

  1. Cord filename = "01-Jan-2019/abcwelcome.pdf"

In this instance, when this particular file is uploaded in Azure Hulk Storage, and so Azure creates a logical group named "01-Jan-2019" then stores the file abcwelcome.pdf within that logical group. But, in normal view every bit from the Azure portal, it will display just like folder file structure the aforementioned as windows explorer.

BlobStorageService.cs

  1. using  Microsoft.WindowsAzure.Storage;
  2. using  Microsoft.WindowsAzure.Storage.Hulk;
  3. using  ServiceLayer.AppConfig;
  4. using  System;
  5. using  System.Collections.Generic;
  6. using  System.IO;
  7. using  System.Threading.Tasks;
  8. namespace  ServiceLayer
  9. {
  10. public class  BlobStorageService
  11.     {
  12. string  accessKey = string .Empty;
  13. public  BlobStorageService()
  14.         {
  15. this .accessKey = AppConfiguration.GetConfiguration( "AccessKey" );
  16.         }
  17. public string  UploadFileToBlob( string  strFileName, byte [] fileData, string  fileMimeType)
  18.         {
  19. effort
  20.             {
  21.                 var _task = Task.Run(() =>this .UploadFileToBlobAsync(strFileName, fileData, fileMimeType));
  22.                 _task.Look();
  23. string  fileUrl = _task.Result;
  24. render  fileUrl;
  25.             }
  26. catch  (Exception ex)
  27.             {
  28. throw  (ex);
  29.             }
  30.         }
  31. public  async void  DeleteBlobData( string  fileUrl)
  32.         {
  33.             Uri uriObj =new  Uri(fileUrl);
  34. string  BlobName = Path.GetFileName(uriObj.LocalPath);
  35.             CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
  36.             CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
  37. string  strContainerName = "uploads" ;
  38.             CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);
  39. string  pathPrefix = DateTime.Now.ToUniversalTime().ToString( "yyyy-MM-dd" ) + "/" ;
  40.             CloudBlobDirectory blobDirectory = cloudBlobContainer.GetDirectoryReference(pathPrefix);
  41.             CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(BlobName);
  42.             look blockBlob.DeleteAsync();
  43.         }
  44. private string  GenerateFileName( string  fileName)
  45.         {
  46. cord  strFileName = string .Empty;
  47. string [] strName = fileName.Separate( '.' );
  48.             strFileName = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd" ) + "/"  + DateTime.Now.ToUniversalTime().ToString( "yyyyMMdd\\THHmmssfff" ) + "."  + strName[strName.Length - 1];
  49. render  strFileName;
  50.         }
  51. private  async Job< string > UploadFileToBlobAsync( string  strFileName, byte [] fileData, cord  fileMimeType)
  52.         {
  53. try
  54.             {
  55.                 CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
  56.                 CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
  57. cord  strContainerName = "uploads" ;
  58.                 CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);
  59. cord  fileName = this .GenerateFileName(strFileName);
  60. if  (await cloudBlobContainer.CreateIfNotExistsAsync())
  61.                 {
  62.                     await cloudBlobContainer.SetPermissionsAsync(new  BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
  63.                 }
  64. if  (fileName != zippo  && fileData != null )
  65.                 {
  66.                     CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
  67.                     cloudBlockBlob.Properties.ContentType = fileMimeType;
  68.                     wait cloudBlockBlob.UploadFromByteArrayAsync(fileData, 0, fileData.Length);
  69. return  cloudBlockBlob.Uri.AbsoluteUri;
  70.                 }
  71. return "" ;
  72.             }
  73. catch  (Exception ex)
  74.             {
  75. throw  (ex);
  76.             }
  77.         }
  78.     }
  79. }

At present, go to the information context layer and create the data context layer for storing the file information in the SQL database using the Entity Framework concept.

IUnitOfWork.cs

  1. using  DataContext;
  2. using  DataContext.Abstractions;
  3. namespace  DataContext
  4. {
  5. public interface  IUnitOfWork
  6.     {
  7.         IProductRepository ProductRepo {get ; }
  8. int  SaveChanges();
  9.     }
  10. }

UnitOfWork.cs

  1. using  DataContext.Abstractions;
  2. using  DataContext.DataContext;
  3. using  DataContext.Implementation;
  4. using  Microsoft.EntityFrameworkCore;
  5. namespace  DataContext
  6. {
  7. public class  UnitOfWork : IUnitOfWork
  8.     {
  9. private  DbContext db;
  10. public  UnitOfWork()
  11.         {
  12.             db =new  EFDBContext();
  13.         }
  14. private  IProductRepository _ProductRepo;
  15. public  IProductRepository ProductRepo
  16.         {
  17. get
  18.             {
  19. if  (_ProductRepo == nix )
  20.                     _ProductRepo =new  ProductRepository(db);
  21. return  _ProductRepo;
  22.             }
  23.         }
  24. public int  SaveChanges()
  25.         {
  26. return  db.SaveChanges();
  27.         }
  28.     }
  29. }

IRepository.cs

  1. using  System.Collections.Generic;
  2. namespace  DataContext.Abstractions
  3. {
  4. public interface  IRepository<TEntity> where TEntity : class
  5.     {
  6. void  Add(TEntity model);
  7.         IEnumerable<TEntity> GetAll();
  8.         TEntity GetById(object  Id);
  9. void  Modify(TEntity model);
  10. void  Delete(TEntity model);
  11. void  DeleteById( object  Id);
  12.     }
  13. }

Repository.cs

  1. using  DataContext.Abstractions;
  2. using  Microsoft.EntityFrameworkCore;
  3. using  System.Collections.Generic;
  4. using  Organisation.Linq;
  5. namespace  DataContext.Implementation
  6. {
  7. public class  Repository<TEntity> : IRepository<TEntity> where TEntity : class
  8.     {
  9. protected  DbContext db { become ; set ; }
  10. public void  Add together(TEntity model)
  11.         {
  12.             db.Fix<TEntity>().Add(model);
  13.         }
  14. public void  Delete(TEntity model)
  15.         {
  16.             db.Prepare<TEntity>().Remove(model);
  17.         }
  18. public void  DeleteById( object  Id)
  19.         {
  20.             TEntity entity = db.Set<TEntity>().Detect(Id);
  21. this .Delete(entity);
  22.         }
  23. public  IEnumerable<TEntity> GetAll()
  24.         {
  25. return  db.Fix<TEntity>().ToList();
  26.         }
  27. public  TEntity GetById( object  Id)
  28.         {
  29. return  db.Set<TEntity>().Find(Id);
  30.         }
  31. public void  Alter(TEntity model)
  32.         {
  33.             db.Entry<TEntity>(model).Land = EntityState.Modified;
  34.         }
  35.     }
  36. }

EFDataContext.cs

  1. using  DataContext.Models;
  2. using  Microsoft.EntityFrameworkCore;
  3. using  System;
  4. using  System.Collections.Generic;
  5. using  Organization.Text;
  6. namespace  DataContext.DataContext
  7. {
  8. public grade  EFDBContext :DbContext
  9.     {
  10. public  EFDBContext()
  11.         {
  12.         }
  13. public  EFDBContext(DbContextOptions<EFDBContext> options) : base (options)
  14.         {
  15.         }
  16. public  DbSet<Product> Product { get ; set ; }
  17. protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  18.         {
  19. if  (!optionsBuilder.IsConfigured)
  20.             {
  21.                 optionsBuilder.UseSqlServer(@"data source=xxxx; initial itemize=ProjectDB;persist security info=True;user id=sa;countersign=xxxxxxx;" );
  22.             }
  23. base .OnConfiguring(optionsBuilder);
  24.         }
  25.     }
  26. }

ProductRepository.cs

  1. using  DataContext.Abstractions;
  2. using  DataContext.DataContext;
  3. using  DataContext.Models;
  4. using  Microsoft.EntityFrameworkCore;
  5. namespace  DataContext.Implementation
  6. {
  7. public form  ProductRepository : Repository<Product>, IProductRepository
  8.     {
  9. private  EFDBContext context
  10.         {
  11. get
  12.             {
  13. return  db as  EFDBContext;
  14.             }
  15.         }
  16. public  ProductRepository(DbContext db)
  17.         {
  18. this .db = db;
  19.         }
  20.     }
  21. }

Footstep xiii

Now, go to the main projects; i.east., MVC Application projects.

Pace 14

Select the Controller folder and add a new MVC Controller Proper noun ProductsController.cs

Step 15

Now, within the controller class, write downwards the below code within the Index Method.

  1. public  IActionResult Index()
  2.         {
  3. return  View(_context.ProductRepo.GetAll());
  4.         }

Step xvi

At present, see a new view against the Index method by clicking the right mouse push. A new view has been added in the view folder. Now add the beneath code in the view file.

  1. @model DataContext.Models.Product
  2. @{
  3.     ViewData["Title" ] = "Details" ;
  4. }
  5. <h2>Details</h2>
  6. <div>
  7.     <h4>Product</h4>
  8.     <hr />
  9.     <dlclass = "dl-horizontal" >
  10.         <dt>
  11.             @Html.DisplayNameFor(model => model.Name)
  12.         </dt>
  13.         <dd>
  14.             @Html.DisplayFor(model => model.Proper name)
  15.         </dd>
  16.         <dt>
  17.             @Html.DisplayNameFor(model => model.UnitPrice)
  18.         </dt>
  19.         <dd>
  20.             @Html.DisplayFor(model => model.UnitPrice)
  21.         </dd>
  22.         <dt>
  23.             @Html.DisplayNameFor(model => model.Description)
  24.         </dt>
  25.         <dd>
  26.             @Html.DisplayFor(model => model.Description)
  27.         </dd>
  28.         <dt>
  29.             @Html.DisplayNameFor(model => model.ImageName)
  30.         </dt>
  31.         <dd>
  32.             @Html.DisplayFor(model => model.ImageName)
  33.         </dd>
  34.         <dt>
  35.             @Html.DisplayNameFor(model => model.ImagePath)
  36.         </dt>
  37.         <dd>
  38.             @Html.DisplayFor(model => model.ImagePath)
  39.         </dd>
  40.         <dt>
  41.             @Html.DisplayNameFor(model => model.CreatedDate)
  42.         </dt>
  43.         <dd>
  44.             @Html.DisplayFor(model => model.CreatedDate)
  45.         </dd>
  46.         <dt>
  47.             @Html.DisplayNameFor(model => model.UpdatedDate)
  48.         </dt>
  49.         <dd>
  50.             @Html.DisplayFor(model => model.UpdatedDate)
  51.         </dd>
  52.     </dl>
  53. </div>
  54. <div>
  55.     <a asp-action="Edit"  asp-road-id= "@Model.ProductId" >Edit</a> |
  56.     <a asp-action="Alphabetize" >Back to Listing</a>
  57. </div>

Stride 17

Now, create a new method for creating in the ProductsController and add related view against that action method.

  1. public  IActionResult Create()
  2.        {
  3. render  View();
  4.        }

Create.cshtml

  1. @model DataContext.Models.Product
  2. @{
  3.     ViewData["Title" ] = "Create" ;
  4. }
  5. <h2>Create</h2>
  6. <h4>Product</h4>
  7. <hr />
  8. @using  (Html.BeginForm( "Create" , "Products" , FormMethod.Post, new  { enctype = "multipart/form-data"  }))
  9. {
  10.     @Html.AntiForgeryToken()
  11.     <divcourse = "form-horizontal" >
  12.         @Html.ValidationSummary(true , "" , new  { @ grade  = "text-danger"  })
  13.         <divclass = "form-group" >
  14.             @Html.LabelFor(model => model.Proper noun, htmlAttributes:new  { @ grade  = "control-characterization col-doc-two"  })
  15.             <divclass = "col-medico-ten" >
  16.                 @Html.EditorFor(model => model.Proper noun,new  { htmlAttributes = new  { @ form  = "form-control"  } })
  17.                 @Html.ValidationMessageFor(model => model.Proper name,"" , new  { @ class  = "text-danger"  })
  18.             </div>
  19.         </div>
  20.         <divclass = "grade-grouping" >
  21.             @Html.LabelFor(model => model.Clarification, htmlAttributes:new  { @ grade  = "control-label col-doc-2"  })
  22.             <divclass = "col-doctor-10" >
  23.                 @Html.EditorFor(model => model.Description,new  { htmlAttributes = new  { @ class  = "form-control"  } })
  24.                 @Html.ValidationMessageFor(model => model.Description,"" , new  { @ grade  = "text-danger"  })
  25.             </div>
  26.         </div>
  27.         <divclass = "form-grouping" >
  28.             @Html.LabelFor(model => model.UnitPrice, htmlAttributes:new  { @ class  = "command-label col-md-2"  })
  29.             <divcourse = "col-medico-x" >
  30.                 @Html.EditorFor(model => model.UnitPrice,new  { htmlAttributes = new  { @ class  = "form-control"  } })
  31.                 @Html.ValidationMessageFor(model => model.UnitPrice,"" , new  { @ grade  = "text-danger"  })
  32.             </div>
  33.         </div>
  34.         <divgrade = "form-group" >
  35.             @Html.LabelFor(model => model.File, htmlAttributes:new  { @ class  = "control-label col-doctor-2"  })
  36.             <divgrade = "col-md-10" >
  37.                 @Html.TextBoxFor(yard => m.File,new  { type = "file"  })
  38.                 @Html.ValidationMessageFor(one thousand => m.File)
  39.             </div>
  40.         </div>
  41.         <divcourse = "form-group" >
  42.             <divcourse = "col-dr.-offset-2 col-md-10" >
  43.                 <input blazon="submit"  value= "Create" grade = "btn btn-default"  />
  44.             </div>
  45.         </div>
  46.     </div>
  47. }
  48. <div>
  49.     <a asp-activeness="Index" >Back to List</a>
  50. </div>
  51. @section Scripts {
  52.     @{wait Html.RenderPartialAsync("_ValidationScriptsPartial" );}
  53. }

Step 18

Now, create an action method for saving the data and write downwardly the beneath code.

  1. [HttpPost]
  2.         [ValidateAntiForgeryToken]
  3. public  IActionResult Create(Product production)
  4.         {
  5. if  (ModelState.IsValid)
  6.             {
  7.                 #region Read File Content
  8.                 var uploads = Path.Combine(env.WebRootPath,"uploads" );
  9. bool  exists = Directory.Exists(uploads);
  10. if  (!exists)
  11.                     Directory.CreateDirectory(uploads);
  12.                 var fileName = Path.GetFileName(product.File.FileName);
  13.                 var fileStream =new  FileStream(Path.Combine(uploads, production.File.FileName), FileMode.Create);
  14. string  mimeType = product.File.ContentType;
  15. byte [] fileData = new byte [product.File.Length];
  16.                 BlobStorageService objBlobService =new  BlobStorageService();
  17.                 production.ImagePath = objBlobService.UploadFileToBlob(product.File.FileName, fileData, mimeType);
  18.