Introduction
In this article, you’ll learn how to upload and view videos using Angular 8 with Web API. we’ll also be creating a demo project for better understanding. This article is very useful for those who are getting started with Angular.
Prerequisites
1. Angular 8
2. ASP.NET Web API
3. SQL Server
4. HTML/Bootstrap
Following Steps are required
- Create a database and two tables in SQL Server
- Build a Web API using ASP.NET Web API
- Create a new project in Angular 8
Create a Database using SQL Server 2016.
So, we’re going to create a database and two tables. For creating the database, we follow the below steps.
Step 1
Connect to the SSMS.
Step 2
Here, we have created the database using the following query.
Create a database db_video
Step 3
CREATE TABLE [dbo].[Video](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Videos] [varchar](50) NULL,
CONSTRAINT [PK_Video] 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 shows in Object Explorer.
Create a Project using ASP.NET Web API
So, here we create a Web API using ASP.NET Web API. we need to follow the below steps.
Step 1
Open Visual Studio 2019 and go to File > New > Project.
Step 2
Select Web >> ASP.NET Web Application.
Step 3
Let’s go and open Solution Explorer.
Step 4
Now, create a new Controller named UploadController.
Step 5
Now, we need to import the database using Entity Framework.
Step 6
Now, here we create a method named “UploadVideoFiles” for inserting video data in the table and upload video in a folder in UploadController.
using WebAPI_Project.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 WebAPI_Project.Controllers
{
public class UploadController : ApiController
{
db_videoDbContext VdoDB = new db_videoDbContext();
[HttpPost()]
public HttpResponseMessage UploadVideoFiles()
{
var httpRequest = HttpContext.Current.Request;
//Upload Image
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("~/Videos/" + filename);
hpf.SaveAs(filePath);
Video obj = new Video();
obj.Videos = "http://localhost:50401/Videos/"+filename;
VdoDB.Videos.Add(obj);
VdoDB.SaveChanges();
}
}
}
catch (Exception ex)
{ }
return Request.CreateResponse(HttpStatusCode.Created);
}
[HttpPost]
public object Videos()
{
return VdoDB.Videos;
}
}
}
Create Project using Angular 8
Now, Let’s go and create an Angular project using Angular 8. we need to follow the below steps.
Step 1
here, we’re going to create a project using following CLI command on command prompt.
ng new fileupload
Step 2
Open Angular project in Visual Studio Code using the following commands.
cd fileupload
code .
Step 3
After that, we need to install Bootstrap in our project angular using the below command in the terminal.
npm install --save bootstrap
Step 4
After installing Bootstrap, we need to import Bootstrap in style.css.
@import '~bootstrap/dist/css/bootstrap.min.css';
Step 5
we have created a class in below code:
export class Video
{
int:number;
Videos:string;
}
Step 6
here, we have declared methods to upload video using the below 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.VideosList();
}
VideosList(): Observable<VideoMaster[]> {
return this.httpService.get<VideoMaster[]>('http://localhost:50401/api/FileUpload/Videos');
}
sMsg: string = '';
ngOnInit() {
this. getvideos();
}
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]);
}
this.httpService.post('http://localhost:50401/api/FileUpload/UploadFiles', frmData).subscribe(
data => {
// SHOW A MESSAGE RECEIVED FROM THE WEB API.
this.sMsg = data as string;
console.log(this.sMsg);
}
);
}
}
Step 7
Insert this below code in app.component.html for shows videos and upload interface.
<!--The content below is only a placeholder and can be replaced.-->
<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()" #videoPlayer>
<source [src]="Video.Videos" type="video/mp4">
</video>
</div>
Now, run the project using the following command.
ng serve