Introduction
In this article, I am going to explain how to upload and view Video 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
- Create a database and 2 tables in SQL Server
- Create a Web API using ASP.NET Web API
- 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 2
Connect to the SSMS.
Step 3
I have created the database using the following query.
create database db_video
Step 4
I have created a Videomaster table.
- CREATE TABLE [dbo].[VideoMaster](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Videos] [varchar](50) NULL,
- CONSTRAINT [PK_VideoMaster] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
Now, the database looks like below.
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.
Step 2
Select Web >> ASP.NET Web Application.
Step 3
Then, select Web API and click OK.
Step 4
Now, create a new Controller named FileUploadController.
Step 5
Now, import the database using Entity Framework.
Step 6
Now, create a method (UploadFiles) for inserting images in the table and save images in a folder in FileUploadController.
- using MvcApplication1.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web;
- using System.Web.Http;
-
- namespace MvcApplication1.Controllers
- {
- public class FileUploadController : ApiController
- {
- db_videoEntities1 wmsEN = new db_videoEntities1();
- [HttpPost()]
- public HttpResponseMessage UploadFiles()
- {
- var httpRequest = HttpContext.Current.Request;
-
- System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
- try
- {
- for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
- {
- System.Web.HttpPostedFile hpf = hfc[iCnt];
- if (hpf.ContentLength > 0)
- {
- var filename = (Path.GetFileName(hpf.FileName));
- var filePath = HttpContext.Current.Server.MapPath("~/Vedios/" + filename);
- hpf.SaveAs(filePath);
- VideoMaster obj = new VideoMaster();
- obj.Videos = "http://localhost:50401/Vedios/"+filename;
- wmsEN.VideoMasters.Add(obj);
- wmsEN.SaveChanges();
- }
- }
- }
- catch (Exception ex)
- { }
- return Request.CreateResponse(HttpStatusCode.Created);
- }
-
- [HttpPost]
- public object Vedios()
- {
- return wmsEN.VideoMasters;
- }
- }
- }
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.
Step 2
Open project in Visual Studio Code using the following commands.
Step 3
Now, we need to install Bootstrap in our project using the following command in the terminal.
- npm install --save bootstrap
Step 4
After installing Bootstrap, we should import Bootstrap in style.css.
- @import '~bootstrap/dist/css/bootstrap.min.css';
Step 5
I have create a class:
- export class VideoMaster
- {
- int:number;
- Videos:string;
- }
Step 6
I have declared methods to upload images using the following code in App.component.ts
- import { Component, ViewChild, ElementRef } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { VideoMaster } from './VideoMaster';
- import { Observable } from 'rxjs';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'fileupload';
- remark = '';
- constructor(private httpService: HttpClient) { }
- myFiles: string[] = [];
- myVideos: Observable<VideoMaster[]>;
-
- @ViewChild('videoPlayer') videoplayer: ElementRef;
-
- toggleVideo(event: any) {
- this.videoplayer.nativeElement.play();
- }
- getvideos() {
- debugger;
- this.myVideos= this.VediosList();
- }
-
- VediosList(): Observable<VideoMaster[]> {
- return this.httpService.get<VideoMaster[]>('http://localhost:50401/api/FileUpload/Vedios');
- }
-
- sMsg: string = '';
- StudentIdUpdate: string;
- ngOnInit() {
- this. getvideos();
- }
-
- getFileDetails(e) {
-
- 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]);
- }
- this.httpService.post('http://localhost:50401/api/FileUpload/UploadFiles', frmData).subscribe(
- data => {
-
- this.sMsg = data as string;
- console.log(this.sMsg);
- }
- );
- }
-
- }
Step 7
Put this code in app.component.html
- <!--The content below is only a placeholder and can be replaced.-->
- <div style="text-align:center">
- <h1>
- Welcome to {{ title }}!
- </h1>
- <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
- </div>
-
- <div class="col-sm-10">
- <ng-container>
- <input type="file" id="file" multiple (change)="getFileDetails($event)">
- <button class="btn btn-primary" (click)="uploadFiles()">Upload</button>
- </ng-container>
- </div>
- <div class="col-sm-10" *ngFor="let Video of myVideos | async; let i=index">
- <video width="270" height="220" controls disabled="true" (click)="toggleVideo()"
- <source [src]="Video.Videos" type="video/mp4">
- </video>
- </div>
Now, run the project using the following command.
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 Reactive Forms Validation using Angular 7.