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:
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.
You can download the source code from here
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
View Comments
It seems like when I host this on AWS I get an error "Upload Failed: Object reference not set to an instance of an object." Any idea why? Thank you.
would you pass image object as class variable of method in .net core api as IFormFile type ?
I got the issue using angular method, single file upload is working good but multiple file upload is not working
Hiya, I am really glad I've found this information. Today bloggers publish just about gossips and net and this is really annoying. A good web site with exciting content, this is what I need. Thanks for keeping this website, I'll be visiting it. Do you do newsletters? Cant find it.
What's the issue? @mathieu cupryk
There is an issue with calling method (upload) from angular.
Thank you
You are welcome!
Thank you for this...
You are welcome!