How To Upload Multiple Images Using Angular 7

Introduction 

 
In this article, I am going to explain how to upload multiple images using angular 7 and Web API. I am also creating a demo project for  better understanding. This article will help beginners who are getting started with Angular.
 
Prerequisites
  • Angular 7
  • Web API
  • SQL Server
  • HTML/Bootstrap 

Steps required

  1. Create a database and 2 tables in SQL Server
  2. Create a Web API using ASP.NET Web API
  3. Create a new project in Angular 7
For this article, I have created a database and two tables. For creating the database, we follow the following steps.
 
Step 1
 
Let's open SSMS (SQL Server Management Studio).
 
How To Upload Multiple Image Using Angular 7 
  
Step 2
 
Connect to the SSMS.
 
How To Upload Multiple Image Using Angular 7
 
Step 3
 
I have created the database using the following query. 
  1. create database db_multipleimage  
Step 4
 
I have created an Imagemaster table. 
  1. CREATE TABLE [dbo].[imagemaster](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [ImageName] [varchar](50) NULL,  
  4.     [Remark] [varchar](50) NULL,  
  5.  CONSTRAINT [PK_imagemaster] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [Id] ASC  
  8. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  9. ON [PRIMARY  
Now, the database looks like below.
 
How To Upload Multiple Image Using Angular 7
 
I have created a Web API using ASP.NET Web API. For creating the Web API, we need to follow the following steps.
 
Step 1
 
Open Visual Studio 2017 and go to File > New > Project.
 
How To Upload Multiple Image Using Angular 7
 
How To Upload Multiple Image Using Angular 7
 
Step 2
 
Select Web >> ASP.NET Web Application.
 
How To Upload Multiple Image Using Angular 7
 
Step 3
 
Then, select Web API and click OK.
 
How To Upload Multiple Image Using Angular 7
 
Step 4
 
Now, create a new Controller named FileUploadController.
 
How To Upload Multiple Image Using Angular 7
 
How To Upload Multiple Image Using Angular 7
 
Step 5
 
Now, import the database using Entity Framework.
 
How To Upload Multiple Image Using Angular 7
 
Step 6
 
Now, create a method (UploadFiles) for inserting images in the table and save images in a folder in FileUploadController.
  1. [HttpPost()]  
  2.        public string UploadFiles()  
  3.        {  
  4.            string sPath = "";  
  5.            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/image/");  
  6.            var request = System.Web.HttpContext.Current.Request;  
  7.            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;  
  8.            var remark = request["remark"].ToString();  
  9.            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)  
  10.            {  
  11.                System.Web.HttpPostedFile hpf = hfc[iCnt];  
  12.                if (hpf.ContentLength > 0)  
  13.                {  
  14.                    string FileName = (Path.GetFileName(hpf.FileName));  
  15.                    if (!File.Exists(sPath + FileName))  
  16.                    {  
  17.                        // SAVE THE FILES IN THE FOLDER.  
  18.                        hpf.SaveAs(sPath + FileName);  
  19.                        imagemaster obj = new imagemaster();  
  20.                        obj.Remark = remark;  
  21.                        obj.ImageName = FileName;  
  22.                        wmsEN.imagemasters.Add(obj);  
  23.                        wmsEN.SaveChanges();  
  24.                    }  
  25.                }  
  26.            }  
  27.            return "Upload Failed";  
  28.        }  
For this article, I have created an Angular project using Angular 7. For creating an Angular project, we need to follow the following steps.
 
Step 1
 
I have created a project using the following command in the Command Prompt.
  1. ng new fileupload  
Step 2
 
Open project in Visual Studio Code using the following commands.
  1. cd fileupload
  1. code .  
How To Upload Multiple Image Using Angular 7
 
Step 3
 
Now, we need to install bootstrap in our project using the following command in the terminal.
  1. npm install --save bootstrap  
Step 4
 
After installing bootstrap, we should import bootstrap in style.css.
  1. @import '~bootstrap/dist/css/bootstrap.min.css';  
Step 5
 
I have declared methods to upload images using the following code in App.component.ts
  1. import { Component } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3.   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent {  
  10.   title = 'fileupload';  
  11.   remark = '';  
  12.   constructor(private httpService: HttpClient) { }  
  13.   myFiles: string[] = [];  
  14.     
  15.   sMsg: string = '';  
  16.   StudentIdUpdate: string;  
  17.   ngOnInit() {}  
  18.     
  19.   getFileDetails(e) {  
  20.     //console.log (e.target.files);  
  21.     for (var i = 0; i < e.target.files.length; i++) {  
  22.       this.myFiles.push(e.target.files[i]);  
  23.     }  
  24.   }  
  25.   uploadFiles() {  
  26.     const frmData = new FormData();  
  27.     for (var i = 0; i < this.myFiles.length; i++) {  
  28.       frmData.append("fileUpload", this.myFiles[i]);  
  29.       if (i == 0) {  
  30.         frmData.append("remark", this.remark);  
  31.       }  
  32.     }  
  33.     this.httpService.post('http://localhost:50401/api/FileUpload/UploadFiles', frmData).subscribe(  
  34.       data => {  
  35.         // SHOW A MESSAGE RECEIVED FROM THE WEB API.  
  36.         this.sMsg = data as string;  
  37.         console.log(this.sMsg);  
  38.       }  
  39.     );  
  40.   }  
  41. }  
Step 6
 
Put this code in app.component.html 
  1. <!--The content below is only a placeholder and can be replaced.-->  
  2. <div style="text-align:center">  
  3.   <h1>  
  4.     Welcome to {{ title }}!  
  5.   </h1>  
  6.   <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">  
  7. </div>  
  8.    
  9. <div class="col-sm-5">  
  10.   <ng-container>  
  11.       <input type="file" id="file" multiple (change)="getFileDetails($event)">  
  12.       <input type="text" [(ngModel)]="remark">  
  13.       <button class="btn btn-primary" (click)="uploadFiles()">Upload</button>  
  14.   </ng-container>  
  15. </div>  
Now, run the project using the following command.
  1. ng serve  
How To Upload Multiple Image Using Angular 7
 
How To Upload Multiple Image Using Angular 7
 
How To Upload Multiple Image Using Angular 7
 
How To Upload Multiple Image Using Angular 7

Summary

 
In this article, I have discussed how to upload multiple images in a Web API using Angular 7. In my next article, I am going to discuss how to upload a video using Angular 7 in a Web API.


Similar Articles