Upload Text File to Aspnet Core Angular
In this article, we are going to take a look at the Azure Storage Platform and learn how to work with Azure BLOB Storage.
We'll outset with an introduction to the Azure Storage Platform. Then, we'll expect at the dissimilar types of storage services that Azure offers. Afterward that, we'll take a deeper look at Azure BLOB storage. Side by side, we are going to learn how to develop an Angular UI app with ASP.Cyberspace Core Web API backend that leverages the Azure Blob Storage. Finally, we'll test the application and verify that everything works as expected.
And then, let's get going.
Azure Storage Platform – Introduction
Microsoft offers Azure Storage Platform as a deject storage solution for all modern data storage scenarios. It offers a highly scalable object store for information objects, a reliable queue-based messaging shop, a NoSQL store, deejay storage for Azure virtual machines, and a deject-based file share platform.
The Azure Storage services offer many advantages over a traditional storage solution:
- Durable and Highly Available: Azure Storage has redundancy enabled by default which ensures that our data is safe in the event of unexpected hardware failures. At that place is also an option to replicate information across data centers or geographical regions for additional protection from local mishaps or natural disasters. Data that we replicate this way will remain highly available in the effect of unexpected outages.
- Secure : The Azure Storage service encrypts all the data that it stores. Additionally, it provides fine-grained control over who tin access that data.
- Scalable : Azure Storage is massively scalable and is designed to meet mod applications' data storage and performance needs.
- Managed : Being a cloud service, Azure handles the hardware maintenance, updates, and critical bug for us and we don't have to worry about any of those.
- Attainable : Data stored in Azure Storage is accessible from anywhere in the world over HTTP. Microsoft provides SDKs for Azure Storage in many languages like .Cyberspace, Java, Node.js, Python, PHP, Ruby, Go, etc. Additionally, information technology is possible to access the storage services via a Residual API, Azure PowerShell or Azure CLI. Furthermore, the Azure portal and the Azure Storage Explorer App provide a visual interface to work with the information stored in Azure Storage.
Types of Azure Storage Services
The Azure Storage platform offers various services that cater to dissimilar scenarios:
- Azure Blobs : Azure Blob Storage offers massively scalable object stores for storing text and binary data. It too includes support for big information analytics through Information Lake Storage Gen2.
- Azure Queues : Microsoft offers Azure Queue Storage as a service for storing big numbers of letters. They tin enable reliable messaging between applications and components.
- Azure Tables : Azure Table storage is an excellent choice if nosotros want to shop structured NoSQL data in the deject. It tin can store key and attribute values without defining a schema.
- Azure Disks : Azure Disks offering managed block-level storage volumes. We can easily adhere them to Azure Virtual Machines.
- Azure Files : Microsoft offers Azure File Storage equally a fully managed cloud file share. We can access them from both cloud and on-premises services.
A Deeper Await at Azure Blob Storage
We have discussed the Azure storage platform and different types of storage services. Now let'southward have a deeper look at the Azure Hulk storage. Microsoft offers Azure Blob storage for storing large object blobs in the deject. This is optimized for storing large amounts of text or binary data.
Blob storage is ideal for many scenarios like:
- Serving images or documents directly through the browser.
- Storing files for access from multiple locations and services.
- Streaming video and audio files.
- Storing data for backup and restore operations, disaster recovery, and archiving, etc.
- Storage for data analysis past both on-premises and Azure-hosted services.
Nosotros can access objects stored in BLOB storage from anywhere in the globe via HTTP or HTTPS. Users or client applications tin admission files stored in BLOB storage via URLs, the Azure Storage Rest API, Azure PowerShell, Azure CLI, or Azure Storage client libraries(SDKs) that are bachelor in diverse languages. In this example, we'll see how to access Azure Blob storage using the .Cyberspace SDK from an ASP.Cyberspace Cadre Web API application.
Hulk storage supports Azure Data Lake Storage Gen2, which is Microsoft's enterprise big data analytics solution designed for the cloud. Azure Data Lake Storage Gen2 offers a hierarchical file organisation in addition to the capabilities of the Blob storage.
Construction of an Azure Blob Storage
Blob storage has 3 types of resource:
- Storage Accounts : A storage business relationship provides a unique namespace in Azure for our data. Every object that we store in Azure Storage has an address that includes the unique account proper name. The combination of the account proper noun and the Azure Storage BLOB endpoint forms the base address for the objects in the storage business relationship.
- Containers : But like how a directory organizes files in a file system, containers organize a set up of blobs. A storage account tin include any number of containers, and a container can store an unlimited number of blobs.
- Blobs : BLOB can store text and binary information. Blob storage offers three types of blobs – Cake blobs , Append blobs , and Page blobs . We can specify the blob type while creating the blob. It is not possible to alter its type afterward and nosotros tin only update a blob file using the operations appropriate for that item blob blazon, for instance, nosotros tin only write a cake or listing of blocks to a block blob, append blocks to an append blob, and write pages to a page blob.
We can represent the construction of Hulk storage this way:
We have discussed the concepts of Azure Blob storage in detail. At present it'southward fourth dimension to become hands-on by building an application that connects with Azure Blob storage.
Building an App to Work with Azure BLOB Storage
We have learned how to upload files using an Angular app with the .Cyberspace Core Web API in our How To Upload Files With .Net Core Web API and Angular article. In that example, nosotros shop the uploaded files in a folder inside the web server awarding. Nosotros are going to modify that case to upload files to Azure Blob storage instead. This will also help us understand the changes required for migrating on-premises file storage to Azure Hulk storage.
But earlier we do that, we demand to set up the Azure storage account.
Creating the Storage
We have explained the process of creating an Azure Storage business relationship in the Creating Azure Storage department of the Upload Files to Azure with .Net Core Web API and Blazor WebAssembly article. Following through the article department, allow's create a storage account:
Cool!
Our storage business relationship is ready. Nosotros don't have any containers or BLOBs yet but don't worry, we are going to create those with our app.
The adjacent stride is configuring the Spider web API projection.
Configuring the API
Let's download and set upwards the server application from the Upload Files .NET Core Angular Finished Project Make sure to re-create the connection string of the storage we created and add together it to the appsettings.json
file:
{ ... }, "ConnectionStrings": { "AzureStorage": "DefaultEndpointsProtocol=https;AccountName=codemazestorage;AccountKey=UjBmo......;EndpointSuffix=core.windows.internet" }, "AllowedHosts": "*" }
Make sure that we have installed the Azure.Storage.Hulk
library in the server application. This library helps united states of america to work with the Azure Storage Blob service:
Subsequently that, permit's define a service for handling the upload.
Creating the Service
First, allow's create an interface IUploadService
:
using System.IO; using System.Threading.Tasks; namespace UploadFilesServer.Services { public interface IUploadService { Chore<string> UploadAsync(Stream fileStream, string fileName, cord contentType); } }
After that, let'due south create the UploadService
grade implementing the interface:
using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.Extensions.Configuration; using System.IO; using System.Threading.Tasks; namespace UploadFilesServer.Services { public class UploadService : IUploadService { private readonly cord _storageConnectionString; public UploadService(IConfiguration configuration) { _storageConnectionString = configuration.GetConnectionString("AzureStorage"); } public async Task<string> UploadAsync(Stream fileStream, string fileName, string contentType) { var container = new BlobContainerClient(_storageConnectionString, "file-container"); var createResponse = await container.CreateIfNotExistsAsync(); if (createResponse != null && createResponse.GetRawResponse().Status == 201) expect container.SetAccessPolicyAsync(PublicAccessType.Blob); var blob = container.GetBlobClient(fileName); await blob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots); look blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = contentType }); return blob.Uri.ToString(); } } }
The UploadAsync()
method accepts the file stream, file proper name, and content type every bit parameters. It connects to the storage business relationship using the connection string and creates the container if it does not exist. Later on that, it sets the access for BLOB as public. By doing and so, we are making the documents that we upload to this Hulk public.
Notation: In case nosotros desire to protect the documents, there is an selection to restrict admission to Blob by using a technique chosen Shared Access Signature(SAS). This works by generating a temporary SAS URL using the Azure Storage credentials and then we can use this URL to access the file in the specified period. This is a bit of an advanced topic and exterior the scope of this example
Then we bank check if a Hulk with the same name exists and delete information technology. Afterward that, we upload the Hulk file. Once the upload is complete, we render the Blob URL from the method.
Modifying the Controller
As soon as the upload service is ready, the next footstep is to change the controller to use this service:
using System; using Organisation.Linq; using Organization.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using UploadFilesServer.Services; namespace UploadFilesServer.Controllers { [Route("api/[controller]")] [ApiController] public form UploadController : ControllerBase { individual readonly IUploadService uploadService; public UploadController(IUploadService uploadService) { this.uploadService = uploadService ?? throw new ArgumentNullException(nameof(uploadService)); } [HttpPost, DisableRequestSizeLimit] public async Task<IActionResult> UploadAsync() { try { var formCollection = await Request.ReadFormAsync(); var file = formCollection.Files.Offset(); if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string fileURL = await uploadService.UploadAsync(file.OpenReadStream(), fileName, file.ContentType); return Ok(new { fileURL }); } else { return BadRequest(); } } catch (Exception ex) { render StatusCode(500, $"Internal server mistake: {ex}"); } } } }
In the controller's UploadAsync()
method, we read the uploaded file and so pass the file stream, name, and content type to the UpoadAsync()
method of the service class. Note that the endpoint now returns the full file URL instead of the DB path.
Also, we demand to configure the dependency injection in the ConfigureServices()
method of the Startup
file:
public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<IUploadService, UploadService>(); ... }
That'due south information technology.
The server application is ready. Now permit'south modify the Angular client app.
Modifying the Customer App
We can download and prepare the customer application from the Upload Files .Net Cadre Angular Finished Project git repo. In the client app, start, we need to modify the app.component.ts
file. We need to set the file URL as the epitome path instead of the DB path in the response object and within the onCreate()
method :
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export grade AppComponent implements OnInit { public isCreate: boolean; public name: cord; public address: string; public user: UserToCreate; public users: User[] = []; public response: {fileURL: ''}; constructor(private http: HttpClient){} ngOnInit(){ this.isCreate = truthful; } public onCreate = () => { this.user = { proper name: this.name, address: this.address, imgPath: this.response.fileURL } this.http.post('https://localhost:5001/api/users', this.user) .subscribe(res => { this.getUsers(); this.isCreate = false; }); } ... }
Subsequently this, we can remove the createImgPath()
function as we are non using information technology anymore.
Finally, in the app.component.html
file, nosotros can prepare the epitome URL direct to the paradigm source:
<tr *ngFor="let user of users"> <td><img [src]="user.imgPath" alt="contour movie" way="width:60px; pinnacle:60px;"></td> <td>{{user.proper name}}</td> <td>{{user.accost}}</td> </tr>
Great!
The client app is ready. Permit's test it at present.
Testing the App
For testing the app, we need to kickoff both the server and client applications.
Once both the applications are started, let'due south navigate to the URL of the athwart app http://localhost:4200/
. We tin provide the user details, select an image and click on Create push button:
On submitting this folio, we will exist redirected to the listing page and we can see the user details and the selected image:
Now, let's audit the image and verify its source:
Bully!
We tin can see that the paradigm is at present served from the Azure Blob storage as axiomatic from its source.
Now, let's go to the Azure portal and check the storage account:
We can see that it creates a new container with the proper name we specified and uploads the epitome into information technology.
It is possible to correspond the architecture of the electric current example using the below diagram:
Users access the Angular customer app which communicates with the back-end Web API awarding. The Web API stores the uploaded image in the Azure Blob storage and saves the details in an SQL database.
Conclusion
We take covered the following topics in this article:
- An introduction to Azure storage platform
- Types of Azure storage services
- A deeper look at Azure BLOB storage
- Connecting to Azure Blob storage from .NET Core application using the SDK
So, that's information technology for this one and until the side by side article,
All the all-time.
Source: https://code-maze.com/azure-blob-storage-with-asp-net-core-and-angular/
0 Response to "Upload Text File to Aspnet Core Angular"
Enregistrer un commentaire