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.
Choose a new Angular project in NET Core and select the setup HTTPS box.
Your application has been created. Now, left-click on the ClientApp and open it into the file explorer.
Now, entered cmd as shown in the image.
Now, In the command prompt window, type npm install.
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.
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); } } } }
<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>
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(); }); } }