Introduction

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

Step 1

Open VS2017 and create a new project >>Web >> .NET Core >> ASP.NET Core web application. Now, select the Angular app template and click OK.

ASP.NET Core

Step 2

Now, right click your ClientApp folder and select "Open containing folder".

ASP.NET Core

Step 3

Write cmd on the path and enter and run > npmInstall

ASP.NET Core

Now, your command prompt is open. Write the npm installation command for installing your packages in the Angular app.
npm install
ASP.NET Core

Step 4

Now, run your application and it automatically restores your npm packages.

See your project structure given below.

ASP.NET Core

Step 5

Now, add the file and upload API Controller in your project.
Right click on controller>>new item>>WebApiControllre>>give name UploadController.cs

ASP.NET Core

Step 6

Copy the following code into API controller.
  1. Open fileupload controller and paste this code.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http.Headers;
  7. using System.Threading.Tasks;
  8. using Microsoft.AspNetCore.Hosting;
  9. using Microsoft.AspNetCore.Mvc;
  10. // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
  11. namespace FileUploadAngular5WithAsp.NetCore.Controllers
  12. {
  13. [Produces("application/json")]
  14. [Route("api/[controller]")]
  15. public class UploadController : Controller
  16. {
  17. private IHostingEnvironment _hostingEnvironment;
  18. public UploadController(IHostingEnvironment hostingEnvironment)
  19. {
  20. _hostingEnvironment = hostingEnvironment;
  21. }
  22. [HttpPost, DisableRequestSizeLimit]
  23. public ActionResult UploadFile()
  24. {
  25. try
  26. {
  27. var file = Request.Form.Files[0];
  28. string folderName = "Upload";
  29. string webRootPath = _hostingEnvironment.WebRootPath;
  30. string newPath = Path.Combine(webRootPath, folderName);
  31. if (!Directory.Exists(newPath))
  32. {
  33. Directory.CreateDirectory(newPath);
  34. }
  35. if (file.Length > 0)
  36. {
  37. string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
  38. string fullPath = Path.Combine(newPath, fileName);
  39. using (var stream = new FileStream(fullPath, FileMode.Create))
  40. {
  41. file.CopyTo(stream);
  42. }
  43. }
  44. return Json("Upload Successful.");
  45. }
  46. catch (System.Exception ex)
  47. {
  48. return Json("Upload Failed: " + ex.Message);
  49. }
  50. }
  51. }
  52. }
Step 7

Now, create the file upload component in your Angular project.
  • Right-click on ClientApp and write cmd. Then, write this command: ng g c fileupload

  • g=generate

  • c=cmponent

ASP.NET Core


Now, call the fileupload API from the fileuploadcomponent.ts file.

Step 8

Open the fileupload.component.ts file and paste the code in to it.
  1. import { Component, OnInit } from '@angular/core';
  2. import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';
  3. @Component({
  4. selector: 'app-fileupload',
  5. templateUrl: './fileupload.component.html',
  6. styleUrls: ['./fileupload.component.css']
  7. })
  8. export class FileuploadComponent {
  9. public progress: number;
  10. public message: string;
  11. constructor(private http: HttpClient) { }
  12. upload(files) {
  13. if (files.length === 0)
  14. return;
  15. const formData = new FormData();
  16. for (let file of files)
  17. formData.append(file.name, file);
  18. const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
  19. reportProgress: true,
  20. });
  21. this.http.request(uploadReq).subscribe(event => {
  22. if (event.type === HttpEventType.UploadProgress)
  23. this.progress = Math.round(100 * event.loaded / event.total);
  24. else if (event.type === HttpEventType.Response)
  25. this.message = event.body.toString();
  26. });
  27. }
  28. }

Step 9

Now, open the fileupload.component.html file and paste the code in to it.

  1. <h1>File Upload Using Angular 5 and ASP.NET Core 2.1</h1>
  2. <input #file type="file" multiple (change)="upload(file.files)" />
  3. <br />
  4. <span style="font-weight:bold;color:green;" *ngIf="progress > 0 && progress < 100">
  5. {{progress}}%
  6. </span>
  7. <span style="font-weight:bold;color:green;" *ngIf="message">
  8. {{message}}
  9. </span>

Step 10

Now, add routing for the file upload component in the app.module.ts. Paste this line into RouterModule.forRoot.

  1. { path: 'file-upload', component: FileuploadComponent },

ASP.NET Core

Step 11

Now, add the menu for the file upload in nav-menu.component.html.

Add this code under <ul> tag.
  1. <li [routerLinkActive]='["link-active"]'>
  2. <a [routerLink]='["/file-upload"]' (click)='collapse()'>
  3. <span class='glyphicon glyphicon-th-list'></span> File Upload
  4. </a>
  5. </li>
Let us see the output

ASP.NET Core

You can check all this code from my GitHub here.

Summary

So here, we have added the file upload functionality to an Angular 5 app with ASP.NET Core 2.. If you have any query or want to give feedback, please comment below.