How To Upload Multiple Images /Files into Database Using Angular web Api
Introduction
In this article, I am going to explain how to upload multiple images using angular 8 and Web API, This article will help beginners who are getting started with Angular.
Prerequisites
- Angular 8
- Web API
- SQL Server
- HTML/Bootstrap
Steps required
- Create a database and tables in SQL Server
- Create a Web API using ASP.NET Web API
- Create a new project in Angular
Create Database using Sql server
create database db_multiplefile
Create Table using using below fileds
Id ,ImageName, and remark
Id ,ImageName, and remark
I Have Created Web Api Project using Visual studio 2019
Now Create Edmx for Dababase Operations
Now Create a Empty controller I Have Created Controller name FileUploadController
I am sharing all code that I have written for controller
using FilesUpload.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace FilesUpload.Controllers
{
public class FileUploadController : ApiController
{
db_multipleimageEntities db = new db_multipleimageEntities();
[HttpPost()]
[ActionName("UploadFiles")]
public string GetFiles()
{
string sPath = "";
sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/");
var request = System.Web.HttpContext.Current.Request;
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
var remark = request["remark"].ToString();
try
{
for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
{
System.Web.HttpPostedFile hpf = hfc[iCnt];
if (hpf.ContentLength > 0)
{
string FileName = (Path.GetFileName(hpf.FileName));
if (!File.Exists(sPath + FileName))
{
// SAVE THE FILES IN THE FOLDER.
hpf.SaveAs(sPath + FileName);
imagemaster obj = new imagemaster();
obj.Remark = remark;
obj.ImageName = FileName;
db.imagemasters.Add(obj);
db.SaveChanges();
}
}
}
}
catch (Exception ex)
{
throw;
}
return "Upload Failed";
}
}
}
Now Time to create Angular Project using below command
ng new fileupload
Open project in Visual Studio Code using the following commands.
cd fileupload
code .
Now, we need to install bootstrap in our project using the following command in the terminal.
npm install --save bootstrap
After installing bootstrap, we should import bootstrap in style.css.
@import '~bootstrap/dist/css/bootstrap.min.css';
I have declared methods to upload images using the following code in App.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'fileupload';
remark='';
constructor(private httpService: HttpClient){}
myFiles: string[] = [];
sMsg: string = '';
StudentIdUpdate: string;
ngOnInit() {}
getFileDetails(e) {
//console.log (e.target.files);
for (var i = 0; i < e.target.files.length; i++) {
this.myFiles.push(e.target.files[i]);
}
}
uploadFiles() {
const frmData = new FormData();
for (var i = 0; i < this.myFiles.length; i++) {
frmData.append("fileUpload", this.myFiles[i]);
if (i == 0) {
frmData.append("remark", this.remark);
}
}
this.httpService.post('https://localhost:44378/api/FileUpload/UploadFiles',
frmData).subscribe(
data => {
// SHOW A MESSAGE RECEIVED FROM THE WEB API.
this.sMsg = data as string;
console.log(this.sMsg);
}
);
}
}
Now go to App component.html
<router-outlet></router-outlet>
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64"</div>
<div class="col-sm-5" class="solid">
<ng-container>
<input type="file" id="file" multiple (change)="getFileDetails($event)">
<input type="text" [(ngModel)]="remark">
<button type="button" class="btn btn-success">Upload</button>
<button class="btn btn-primary" (click)="uploadFiles()">Upload</button>
</ng-container>
</div>
Now go to app module.ts and import
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
Imports : into array
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
],
Time to run Project using below command and see the Result
Ng serve
Go to Database and check whether file is uploaded or not
Summery : In this Blog, I have Shown you how to upload multiple images in a Web API using Angular 8
Comments
Post a Comment