How To Upload And View Video Using Angular 7

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

  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.
 
How To Upload And View Video Using Angular 7
 
Step 2
 
Connect to the SSMS.
 
How To Upload And View Video Using Angular 7
 
Step 3
 
I have created the database using the following query.
 
create database db_video
 
Step 4
 
I have created a Videomaster table. 
  1. CREATE TABLE [dbo].[VideoMaster](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Videos] [varchar](50) NULL,    
  4.  CONSTRAINT [PK_VideoMaster] PRIMARY KEY CLUSTERED     
  5. (    
  6.     [Id] ASC    
  7. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]    
  8. ON [PRIMARY]    
Now, the database looks like below.
 
How To Upload And View Video 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 And View Video Using Angular 7
 
How To Upload And View Video Using Angular 7
 
Step 2
 
Select Web >> ASP.NET Web Application.
 
How To Upload And View Video Using Angular 7
 
Step 3
 
Then, select Web API and click OK.
 
How To Upload And View Video Using Angular 7
 
Step 4
 
Now, create a new Controller named FileUploadController.
 
How To Upload And View Video Using Angular 7
 
How To Upload And View Video Using Angular 7
 
Step 5
 
Now, import the database using Entity Framework.
 
How To Upload And View Video 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. using MvcApplication1.Models;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.IO;    
  5. using System.Linq;    
  6. using System.Net;    
  7. using System.Net.Http;    
  8. using System.Web;    
  9. using System.Web.Http;    
  10.     
  11. namespace MvcApplication1.Controllers    
  12. {    
  13.     public class FileUploadController : ApiController    
  14.     {    
  15.         db_videoEntities1 wmsEN = new db_videoEntities1();    
  16.         [HttpPost()]    
  17.         public HttpResponseMessage UploadFiles()    
  18.         {    
  19.             var httpRequest = HttpContext.Current.Request;    
  20.             //Upload Image    
  21.             System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;    
  22.             try    
  23.             {    
  24.                 for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)    
  25.                 {    
  26.                     System.Web.HttpPostedFile hpf = hfc[iCnt];    
  27.                     if (hpf.ContentLength > 0)    
  28.                     {    
  29.                         var filename = (Path.GetFileName(hpf.FileName));    
  30.                         var filePath = HttpContext.Current.Server.MapPath("~/Vedios/" + filename);    
  31.                         hpf.SaveAs(filePath);    
  32.                         VideoMaster obj = new VideoMaster();    
  33.                         obj.Videos = "http://localhost:50401/Vedios/"+filename;    
  34.                         wmsEN.VideoMasters.Add(obj);    
  35.                         wmsEN.SaveChanges();    
  36.                     }    
  37.                 }    
  38.             }    
  39.             catch (Exception ex)    
  40.             { }    
  41.             return Request.CreateResponse(HttpStatusCode.Created);    
  42.         }    
  43.     
  44.        [HttpPost]    
  45.         public object Vedios()    
  46.         {    
  47.             return wmsEN.VideoMasters;    
  48.         }    
  49.     }    
  50. }  
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 And View Video 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 create a class:
  1. export class VideoMaster  
  2. {  
  3.      int:number;  
  4.      Videos:string;  
  5. }  
Step 6
 
I have declared methods to upload images using the following code in App.component.ts
  1. import { Component, ViewChild, ElementRef } from '@angular/core';      
  2. import { HttpClient } from '@angular/common/http';      
  3. import { VideoMaster } from './VideoMaster';    
  4. import { Observable } from 'rxjs';    
  5.       
  6. @Component({      
  7.   selector: 'app-root',      
  8.   templateUrl: './app.component.html',      
  9.   styleUrls: ['./app.component.css']      
  10. })      
  11. export class AppComponent {      
  12.   title = 'fileupload';      
  13.   remark = '';      
  14.   constructor(private httpService: HttpClient) { }      
  15.   myFiles: string[] = [];      
  16.   myVideos: Observable<VideoMaster[]>;    
  17.        
  18.   @ViewChild('videoPlayer') videoplayer: ElementRef;    
  19.     
  20.   toggleVideo(event: any) {    
  21.       this.videoplayer.nativeElement.play();    
  22.   }    
  23.   getvideos() {    
  24.     debugger;    
  25.    this.myVideos= this.VediosList();    
  26.   }    
  27.     
  28.   VediosList(): Observable<VideoMaster[]> {    
  29.     return this.httpService.get<VideoMaster[]>('http://localhost:50401/api/FileUpload/Vedios');    
  30.   }    
  31.     
  32.   sMsg: string = '';      
  33.   StudentIdUpdate: string;      
  34.   ngOnInit() {    
  35.     this. getvideos();    
  36.   }      
  37.         
  38.   getFileDetails(e) {      
  39.     //console.log (e.target.files);      
  40.     for (var i = 0; i < e.target.files.length; i++) {      
  41.       this.myFiles.push(e.target.files[i]);      
  42.     }      
  43.   }      
  44.   uploadFiles() {      
  45.     const frmData = new FormData();      
  46.     for (var i = 0; i < this.myFiles.length; i++) {      
  47.       frmData.append("fileUpload"this.myFiles[i]);      
  48.     }      
  49.     this.httpService.post('http://localhost:50401/api/FileUpload/UploadFiles', frmData).subscribe(      
  50.       data => {      
  51.         // SHOW A MESSAGE RECEIVED FROM THE WEB API.      
  52.         this.sMsg = data as string;      
  53.         console.log(this.sMsg);      
  54.       }      
  55.     );      
  56.   }    
  57.        
  58. }    
Step 7
 
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-10">    
  10.   <ng-container>    
  11.       <input type="file" id="file" multiple (change)="getFileDetails($event)">    
  12.       <button class="btn btn-primary" (click)="uploadFiles()">Upload</button>    
  13.   </ng-container>    
  14. </div>  
  15. <div class="col-sm-10" *ngFor="let Video of myVideos | async; let i=index">  
  16.   <video width="270" height="220"   controls disabled="true"  (click)="toggleVideo()" #videoPlayer>   
  17.     <source [src]="Video.Videos" type="video/mp4">   
  18.   </video>  
  19. </div>   
 Now, run the project using the following command.
  1. ng serve    
How To Upload And View Video Using Angular 7
 
How To Upload And View Video Using Angular 7
 
How To Upload And View Video Using Angular 7
 
How To Upload And View Video 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 Reactive Forms Validation using Angular 7.