How To Upload File In Angular 5 With ASP.NET Core In VS 2017

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.   
  11. // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
  12.   
  13. namespace FileUploadAngular5WithAsp.NetCore.Controllers  
  14. {  
  15.     [Produces("application/json")]  
  16.     [Route("api/[controller]")]  
  17.     public class UploadController : Controller  
  18.     {  
  19.         private IHostingEnvironment _hostingEnvironment;  
  20.   
  21.         public UploadController(IHostingEnvironment hostingEnvironment)  
  22.         {  
  23.             _hostingEnvironment = hostingEnvironment;  
  24.         }  
  25.   
  26.         [HttpPost, DisableRequestSizeLimit]  
  27.         public ActionResult UploadFile()  
  28.         {  
  29.             try  
  30.             {  
  31.                 var file = Request.Form.Files[0];  
  32.                 string folderName = "Upload";  
  33.                 string webRootPath = _hostingEnvironment.WebRootPath;  
  34.                 string newPath = Path.Combine(webRootPath, folderName);  
  35.                 if (!Directory.Exists(newPath))  
  36.                 {  
  37.                     Directory.CreateDirectory(newPath);  
  38.                 }  
  39.                 if (file.Length > 0)  
  40.                 {  
  41.                     string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');  
  42.                     string fullPath = Path.Combine(newPath, fileName);  
  43.                     using (var stream = new FileStream(fullPath, FileMode.Create))  
  44.                     {  
  45.                         file.CopyTo(stream);  
  46.                     }  
  47.                 }  
  48.                 return Json("Upload Successful.");  
  49.             }  
  50.             catch (System.Exception ex)  
  51.             {  
  52.                 return Json("Upload Failed: " + ex.Message);  
  53.             }  
  54.         }  
  55.   
  56.     }  
  57. }  
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.   
  4. @Component({  
  5.   selector: 'app-fileupload',  
  6.   templateUrl: './fileupload.component.html',  
  7.   styleUrls: ['./fileupload.component.css']  
  8. })  
  9. export class FileuploadComponent {  
  10.   public progress: number;  
  11.   public message: string;  
  12.   constructor(private http: HttpClient) { }  
  13.   
  14.   upload(files) {  
  15.     if (files.length === 0)  
  16.       return;  
  17.   
  18.     const formData = new FormData();  
  19.   
  20.     for (let file of files)  
  21.       formData.append(file.name, file);  
  22.   
  23.     const uploadReq = new HttpRequest('POST', `api/upload`, formData, {  
  24.       reportProgress: true,  
  25.     });  
  26.   
  27.     this.http.request(uploadReq).subscribe(event => {  
  28.       if (event.type === HttpEventType.UploadProgress)  
  29.         this.progress = Math.round(100 * event.loaded / event.total);  
  30.       else if (event.type === HttpEventType.Response)  
  31.         this.message = event.body.toString();  
  32.     });  
  33.   }  
  34. }  

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.   
  8. <span style="font-weight:bold;color:green;" *ngIf="message">  
  9.   {{message}}  
  10. </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.


Similar Articles