Upload Files into Azure blob storage with ASP.NET Core Web API
We are going to divide this article into the following sections:
· Upload Files to Azure with ASP.NET Core Web API
1. Creating Azure Storage
The first thing we have to do is to navigate and
sign in to Azure Portal where we can create our storage. If we
don’t have a subscription we can create a free subscription account on the
dashboard.
Next, we are going to create a new storage
account service:
After these steps, we are going to click
the Next
button
two times until our validation passes:
2. we are going to modify the appsettings.json
file by adding a connection string section:
{
"ConnectionStrings": {
"EmployeeAppcon": "Data Source=****.mysql.database.azure.com;initial
catalog=databaseName;User id=****; Pwd=***"
"AzureBlobStorage": "DefaultEndpointsProtocol=https;AccountName=authoringsite;AccountKey=X+5571rJNdsg/T7p8WPsTlG/n+KNACPXzkPshpW59y0L9UDReETid8ncxokMTb7Cml9QBKaOG7HpZ2VgLd3SgA==;EndpointSuffix=core.windows.net"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
We can find this connection string in the Access keys
menu that we already have opened:
3. Next create a
new project in visual studio.
4.
Select ASP.Net Core Web Application.
6. Select Target Framework and click on Create button.
7. Once project is create basic view in solution explore.
8.
We need to create two folder with names controllers and models.
9.
Need to install dependency from Genet packages.
MySql.Data.dll
Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll
– version 3.1.10
Azure.Storage.Blobs –
version 12.1.0
10. Please update below line in startup.js
// added scope
to azure blob storage
services.AddScoped(x => new
BlobServiceClient(Configuration.GetValue<string>("ConnectionStrings:AzureBlobStorage")));
11. Next we need to create AssetUploadController.cs
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using createwebapiusingmysql.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace createwebapiusingmysql.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AssetUploadController : Controller
{
private readonly string
_azureConnectionString;
private readonly string
_azureConnectionStringsastoken;
private readonly IConfiguration _configuration;
public AssetUploadController(IConfiguration configuration)
{
_azureConnectionString =
configuration.GetConnectionString("AzureBlobStorage");
_azureConnectionStringsastoken =
configuration.GetConnectionString("SASToken");
_configuration = configuration;
}
List<Products> _category = new List<Products>();
[HttpPost("{id}")]
public async
Task<IActionResult> assetAsync(int id)
{
try
{
GetcategoryFriendlyame(id);
string containersname = _category[0].categoryFriendlyame;
var formCollection = await Request.ReadFormAsync();
var file = formCollection.Files.First();
if (file.Length > 0)
{
var container = new
BlobContainerClient(_azureConnectionString, containersname);
var createResponse = await container.CreateIfNotExistsAsync();
if (createResponse != null &&
createResponse.GetRawResponse().Status == 201)
await
container.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob);
var blob =
container.GetBlobClient(file.FileName);
await
blob.DeleteIfExistsAsync((Azure.Storage.Blobs.Models.DeleteSnapshotsOption)Azure.Storage.Blobs.Models.DeleteSnapshotsOption.IncludeSnapshots);
using (var fileStream = file.OpenReadStream())
{
await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType =
file.ContentType });
blob.SetMetadata(new Dictionary<string, string>());
Dictionary<string, string> metadata = new Dictionary<string, string>(2);
metadata.Add("ProductId", id.ToString());
blob.SetMetadata(metadata);
}
if (blob.Uri.ToString() != null && blob.Uri.ToString() != "")
{
UpdateProductTable(id.ToString(), blob.Uri.ToString());
}
return Ok(blob.Uri.ToString());
}
return BadRequest();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server
error: {ex}");
}
}
// we are
getting category name to create container in azure
private List<Products> GetcategoryFriendlyame(int id)
{
var @ProductId = id;
string query = @"select
categoryFriendlyame,ProductId from restapi.categories,restapi.products where
categories.categoryid = products.categoryid AND products.ProductId=" + @ProductId + ";";
//query =
query.Replace("{id}", id);
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
{
//mycommond.Parameters.AddWithValue("@ProductId", id);
myReader =
mycommond.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
for (int i = 0; i
< table.Rows.Count; i++)
{
Products prd = new Products();
prd.ProductId =
Convert.ToInt32(table.Rows[i]["ProductId"]);
prd.categoryFriendlyame =
table.Rows[i]["categoryFriendlyame"].ToString();
_category.Add(prd);
}
return (_category);
}
}
// We are
updating image and model url to filed in product table
private void
UpdateProductTable(string v1, string v2)
{
string imageuri = v2;
var splitVals = imageuri.Split('/');
var URL4 = splitVals[3];
var URL5 = splitVals[4];
string subseturi = "https://ceeademocontent.azureedge.net";
var sastoken = _azureConnectionStringsastoken;
string finalurl = "" + subseturi + "/" + URL4 + "/" + URL5 + sastoken;
string imagetype = URL5.Substring(URL5.Length - 4);
string query;
if (imagetype.ToString() == "gltf" || imagetype.ToString() == ".glb")
{
query = @"update restapi.Products set productModel = '{finalurl}'
where productId = {v1}";
query = query.Replace("{finalurl}", finalurl);
query = query.Replace("{v1}", v1);
}
else
{
query = @"update restapi.Products set productPreview = '{finalurl}'
where productId = {v1}";
query = query.Replace("{finalurl}", finalurl);
query = query.Replace("{v1}", v1);
}
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
{
myReader =
mycommond.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
}
//return new
JsonResult(table);
}
}
}
Reference Link:
https://code-maze.com/upload-files-to-azure-aspnet-core-blazor-webassembly/
https://code-maze.com/download-files-from-azure-with-net-core-web-api-and-blazor-webassembly/
Comments
Post a Comment