Upload(Pathstring: String

In this blog postal service I desire to show how to upload files from an Angular awarding over an ASP.NET Core WebAPI to an Azure Hulk Storage and save them there. Using an Azure Blob Storage for this is a perfect candidate not to pollute your App Service and store files in that location simply utilize a defended organization for this. In this blog mail service we volition see how we can create the Azure Hulk Storage in the Azure Portal, add together the appropriate services into an ASP.Cyberspace Core WebAPI and add an Athwart Client to upload the files.

GitHub Repository

TOC

  • Create the Azure Blob Storage
  • The ASP.Net Cadre WebAPI
    • Installing the NuGet parcel
    • Modifying the app settings
    • Registering the service
    • Creating a blob service
    • Using the service in a controller
  • Creating the Angular App
    • The UploadService
    • The Uploading Component

Create the Azure Blob Storage

Create the blob storage by entering your dashboard and select "Create Storage Account"

Azure Dashboard Create New Storage Account

You tin can give it a proper noun

Azure Dashboard Naming New Storage Account

then leave all the default values and click until "Review and Create" and then Create your Azure Storage Account.

When the Azure Storage Account is created you can go to the resource and hit the "Container" Button.

Azure Storage Account Resource Container Button

We create a new container, set information technology to "Public access level" "Blob" and give information technology a name. firstcontainer in this example.

Azure Storage Account Resource Container Button

Then click "Create".

Inside of the container you tin can come across no files yet, we will upload them with Angular and ASP.Internet Cadre. Read on 😉

Azure Storage Account Resource Inside Container

If y'all become dorsum into the Container Overview you tin can choose the "Access keys" in the menu on the left and then copy the commencement Connectedness string mentioned at that place.

Azure Storage Account Connection String

We need this for later.

And that is it for setting upwardly the Azure Blob Storage.

Let us move on and create the ASP.Net Core WebAPI.

The ASP.Internet Core WebAPI

Installing the NuGet parcel

To upload files to the blob storage we will create a few services within of the API which will communicate with our Azure Hulk Storage. Earlier nosotros do this we need to add together a NuGet parcel:

NuGet Azure Storage Blobs Package

You can check if and which version o the package is installed by checking your *.csproj file to discover an entry similar this:

                              <Project                Sdk=                "Microsoft.Cyberspace.Sdk"                >                // ...                <ItemGroup>                <PackageReference                Include=                "Azure.Storage.Blobs"                Version=                "<VERSION_HERE>"                />                // ...                </ItemGroup>                // ...                </Projection>                          

Modifying the app settings

Now let us enter the appsettings.json file to add an entry called AzureBlobStorage and paste the connectedness cord you copied here

              {                //                ...                "AzureBlobStorage":                "<SUPER_SECRET_CONNECTION_STRING>"                }                          

Registering the service

In the Startup.cs file nosotros can now register a BlobServiceClient into our services container using the namespace Azure.Storage.Blobs and pass it the previously added value from the configuration.

                              using                Azure.Storage.Blobs;                public                void                ConfigureServices(IServiceCollection services) {                // ...                                                services.AddScoped(x =>                new                BlobServiceClient(Configuration.GetValue<string>("AzureBlobStorage")));                // ...                                }                          

Creating a blob service

Having done that nosotros can inject the BlobServiceClient into a service BlobService we create adjacent.

                              public                form                BlobService                : IBlobService {                individual                readonly                BlobServiceClient _blobServiceClient;                public                BlobService(BlobServiceClient blobServiceClient)     {         _blobServiceClient = blobServiceClient;     }                public                async                Job<Uri> UploadFileBlobAsync(string                blobContainerName, Stream content,                cord                contentType,                string                fileName)     {                var                containerClient = GetContainerClient(blobContainerName);                var                blobClient = containerClient.GetBlobClient(fileName);                await                blobClient.UploadAsync(content,                new                BlobHttpHeaders { ContentType = contentType });                return                blobClient.Uri;     }                private                BlobContainerClient GetContainerClient(string                blobContainerName)     {                var                containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);         containerClient.CreateIfNotExists(PublicAccessType.Hulk);                return                containerClient;     } }                          

The method UploadFileBlobAsync uploads a file to the blob storage we created using the BlobServiceClient. Get-go, nosotros get the container client and phone call CreateIfNotExists on it.

This will ensure the container is there when we upload something into information technology. Withal if you practise not want to allow your API decide which containers to exist created or practice this when seeding or not in the api at all you have to remove or motility this line to some other place. 😊

When returned the containerClient we create a blobClient and upload information technology setting the content type and returning the Uri object here.

Annals the service with its interface in the Startup.cs as following

              services.AddScoped<IBlobService, BlobService>();                          

Using the service in a controller

Inside our controller we tin now inject the service and telephone call the method to upload the file size. Nosotros are reacting to a Mail request and reading the file from the Request object and render a JSON with a belongings path containing the accented path to the resource we uploaded.

Note that nosotros are using the DisableRequestSizeLimit hither for demo. Maybe you want to remove this in production apps. Equally a blobContainerName param nosotros are passing the proper noun of the container we want to shop our data in. We created this before when calculation the storage in Azure but with our code a new i will exist created also automatically for us.

                              using                ...                namespace                backend.Controllers {                                  [ApiController]                                  [Route("api/[controller]                ")]                                                public                class                UploadController                : ControllerBase     {                private                IBlobService _blobService;                public                UploadController(IBlobService blobService)         {             _blobService = blobService;         }                                                                  [HttpPost(""), DisableRequestSizeLimit]                public                async                Task<ActionResult> UploadProfilePicture()         {             IFormFile file = Request.Form.Files[0];                if                (file ==                zero)             {                return                BadRequest();             }                var                outcome =                await                _blobService.UploadFileBlobAsync(                "firstcontainer",                     file.OpenReadStream(),                     file.ContentType,                     file.FileName);                var                toReturn = effect.AbsoluteUri;                return                Ok(new                { path = toReturn });         }     } }                          

Our upload url will be <domain>/api/upload so.

That is it for the backend, we have to add the frontend now and create an Athwart app which will upload the files for us.

Creating the Angular App

The Angular app is pretty straight forward. Commencement let us create an UploadService which communicates to the backend.

The UploadService

                              import                {                HttpClient                }                from                '@angular/common/http';                import                {                Injectable                }                from                '@athwart/core';                @Injectable({                providedIn                :                'root'                })                export                class                UploadService                {                constructor(private                http:                HttpClient) {}                upload(formData:                FormData) {                return                this.http.post                <{                path:                cord                }>(                'https://localhost:5001/api/upload',                formData                );   } }                          

In the app.module.ts the HttpClientModule has to exist added to the imports as well.

                              import                {                HttpClientModule                }                from                '@angular/mutual/http';                import                {                NgModule                }                from                '@angular/core';                import                {                BrowserModule                }                from                '@athwart/platform-browser';                import                {                AppComponent                }                from                './app.component';                @NgModule({                imports                :                [BrowserModule,                HttpClientModule],                declarations                :                [AppComponent],                bootstrap                :                [AppComponent], })                export                class                AppModule                {}                          

The Uploading Component

In the components template we use a push button to open a subconscious file input and nosotros are setting the filename of the selected file and then the user knows that a file was created. A relieve button then calls a save() method where the files are getting passed and kicks of the saving progress

              <push                type                =                "button"                (                click                )="                fileInput                .                click                ()">Choose File</button> <input                subconscious                #                fileInput                blazon                =                "file"                id                =                "file"                (                change                )="                setFilename                (                fileInput                .                files                )"                /> <label>{{ filename }}</characterization> <br                /> <button                type                =                "button"                (                click                )="                relieve                (                fileInput                .                files                )">Relieve</button> <br                /> <img                [                src                ]="                imageSource                "                />                          

The component class gets injected the UploadService and calls the upload method passing the form data. When the call comes back we are extracting the path belongings and setting it as epitome source to display the picture we uploaded.

                              import                {                Component                }                from                '@angular/core';                import                {                UploadService                }                from                './upload.service';                @Component({                selector                :                'app-root',                templateUrl                :                './app.component.html',                styleUrls                :                ['./app.component.css'], })                export                class                AppComponent                {                filename                =                '';                imageSource                =                '';                constructor(private                uploadService:                UploadService) {}                setFilename(files) {                if                (files[0]) {                this.filename                =                files[0].name;     }   }                salve(files) {                const                formData                =                new                FormData();                if                (files[0]) {                formData.append(files[0].name,                files[0]);     }                this.uploadService                .upload(formData)       .subscribe(({                path                })                =>                (this.imageSource                =                path));   } }                          

Angular App showing the uploaded picture

And we can see the file in the hulk container.

Azure Container showing the uploaded picture

GitHub Repository

And that is it, hope it helps!

Fabian

Other blogposts

  • tap, map & switchMap explained
  • Implement endless scroll with Angular, NgRx and ASP.Internet Core WebAPI
  • WebHooks with ASP.NET on Azure - DropBox and GitHub
  • Getting started with Visual Studio Code, AngularJS and Typescript
  • Working with Angular Template Forms

murillowastumpaboos.blogspot.com

Source: https://offering.solutions/blog/articles/2020/08/09/uploading-files-to-azure-blob-storage-with-angular-and-asp.net-core/

0 Response to "Upload(Pathstring: String"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel