In this article, we will see how to upload a file into the database using the Angular 7 app in an ASP.NET project. Let us create a new project in Visual Studio 2017. We are using ASP.NET Core 2 and Angular 7 for this project.

Prerequisites:

  • Node JS must be installed
  • Angular CLI must be installed
  • Basic knowledge of Angular

Let’s get started.

Create a new project and name it as FileUploadInAngular7

Select a new project with Angular in .NET Core and uncheck the configure HTTPS

Your project will be created. Left click on ClientApp and open it in file explorer

Type cmd as shown in the picture.

Type npm install in the cmd

Now it will take time and all the node_modules will be installed in the project.

Create a Web API controller as UploadController.

Add the following code in it.

using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
namespace FileUploadInAngular7.Controllers
{
    [Produces("application/json")]
    [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("Upload Successful.");
            }
            catch (System.Exception ex)
            {
                return Json("Upload Failed: " + ex.Message);
            }
        }
    }
}

Navigate to the following path and open both the files.

In home.component.html write the following code.

<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>

In home.component.ts file write the following code in it.

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();
    });
  }
}

Run the project and you will see the following output.