File Upload In Angular With .NET Core API

File Upload In Angular With .NET Core API

In this article, we will learn how to upload a file into the Angular application using ASP.NET  core API. Let us create a new project in Visual Studio 2022. We are using ASP.NET Core 5 and Angular 14 for this example.

So, Let's start,

Create a new project namely as FileUploadInAngular.

File Upload In Angular With .NET Core API

File Upload In Angular With .NET Core API

Choose a new Angular project in NET Core and select the setup HTTPS box.

File Upload In Angular With .NET Core API

Your application has been created. Now, left-click on the ClientApp and open it into the file explorer.

File Upload In Angular With .NET Core API


Now, entered cmd as shown in the image.

File Upload In Angular With .NET Core API


Now, In the command prompt window, type npm install.

File Upload In Angular With .NET Core API


All of the node modules will now need to be installed in the project, which will take some time.

Make a new UploadController into the Web API controller.

File Upload In Angular With .NET Core API

File Upload In Angular With .NET Core API


Now, Add the following code under the FileUploadInAngularController:

using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace FileUploadInAngular.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        private IHostingEnvironment _hostingEnvironment;

        public UploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost, DisableRequestSizeLimit]
        public ActionResult UploadFile()
        {
            try
            {
                var file = Request.Form.Files[0];
                string folderName = "Upload";
                string webRootPath = _hostingEnvironment.WebRootPath;
                string newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string fullPath = Path.Combine(newPath, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
                return Json("File Upload successfully.");
            }
            catch (System.Exception ex)
            {
                return Json("Upload Failed: " + ex.Message);
            }
        }

    }
}

Now, Open the both files by choosing the following directory.

File Upload In Angular With .NET Core API


Now put the following code into the home.component.html file.

<h1>File Upload Using Angular 7 and ASP.NET Core Web API</h1>
<input #file type="file" multiple (change)="upload(file.files)" />
<br />
<span style="font-weight:bold;color:green;" *ngIf="progress > 0 && progress < 100">
  {{progress}}%
</span>

<span style="font-weight:bold;color:green;" *ngIf="message">
  {{message}}
</span>

Add the following code under the file home.component.ts.

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
})
export class HomeComponent {
  public progress: number;
  public message: string;
  constructor(private http: HttpClient) { }

  upload(files) {
    if (files.length === 0)
      return;

    const formData = new FormData();

    for (let file of files)
      formData.append(file.name, file);

    const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress)
        this.progress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response)
        this.message = event.body.toString();
    });
  }
}

Now, run the project and the results will look like below.

File Upload In Angular With .NET Core API


Conclusion

In this article, we learned how to upload a file in the Angular application using ASP.NET core API. you can also download the source code from my GitHub repository.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post