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.
Step 2
Now, right click your ClientApp folder and select "Open containing folder".
Step 3
Write cmd on the path and enter and run >
npmInstall
Now, your command prompt is open. Write the npm installation command for installing your packages in the Angular app.
npm install
Step 4
Now, run your application and it automatically restores your npm packages.
See your project structure given below.
Step 5
Now, add the file and upload API Controller in your project.
Right click on controller>>new item>>WebApiControllre>>give name UploadController.cs
Step 6
Copy the following code into API controller.
- Open fileupload controller and paste this code.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Mvc;
-
-
-
- namespace FileUploadAngular5WithAsp.NetCore.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);
- }
- }
-
- }
- }
Step 7
Now, create the file upload component in your Angular project.
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.
- import { Component, OnInit } from '@angular/core';
- import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';
-
- @Component({
- selector: 'app-fileupload',
- templateUrl: './fileupload.component.html',
- styleUrls: ['./fileupload.component.css']
- })
- export class FileuploadComponent {
- 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();
- });
- }
- }
Step 9
Now, open the fileupload.component.html file and paste the code in to it.
- <h1>File Upload Using Angular 5 and ASP.NET Core 2.1</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>
Step 10
Now, add routing for the file upload component in the app.module.ts. Paste this line into RouterModule.forRoot.
- { path: 'file-upload', component: FileuploadComponent },
Step 11
Now, add the menu for the file upload in nav-menu.component.html.
Add this code under <ul> tag.
- <li [routerLinkActive]='["link-active"]'>
- <a [routerLink]='["/file-upload"]' (click)='collapse()'>
- <span class='glyphicon glyphicon-th-list'></span> File Upload
- </a>
- </li>
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.