Sunday, 2 August 2020

How To Dynamically Upload And Play Video File Using ASP.NET MVC 5

This article demonstrates how to upload a video file of up to 100MB and play dynamically using ASP.NET MVC 5. I will upload the video file to my project folder name (VideoFileUpload) and add its path in SQL Server database table. I will display all uploaded video files and their names.

Step 1

Create a database in the SQL Server of your choice.

  1. CREATE TABLE [dbo].[VideoFiles](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [FileSize] [int] NULL,  
  5.     [FilePath] [nvarchar](100) NULL,  
  6.  CONSTRAINT [PK_VideoFiles] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [ID] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  10. ) ON [PRIMARY]  
  11.   
  12. GO  
  13.   
  14. CREATE procedure [dbo].[spAddNewVideoFile]  
  15. (  
  16. @Name nvarchar(50),  
  17. @FileSize int,  
  18. @FilePath nvarchar(100)  
  19. )  
  20. as  
  21. begin  
  22. insert into VideoFiles (Name,FileSize,FilePath)   
  23. values (@Name,@FileSize,@FilePath)   
  24. end  
  25.   
  26. CREATE procedure [dbo].[spGetAllVideoFile]  
  27. as  
  28. begin  
  29. select ID,Name,FileSize,FilePath from VideoFiles  
  30. end  

Step 2

Open Visual Studio 2015. Create an empty ASP.NET Web Application project in it. As shown in below screenshot, click on new project >> choose web template >> choose ASP.NET Web Application and give it a meaningful name to click ok.

Screenshot 1

ASP.NET

Choose empty from ASP.NET Templates, select checkbox MVC, and click on OK, as shown in the image below.

Screenshot 2

 

ASP.NET

 

Step 3

Double click and open web config file to add the database connection.

  1. <connectionStrings>  
  2.     <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=MvcDemo; integrated security=true;" />     
  3.   </connectionStrings>  

Add the below code in webconfig file to allow 100MB file to upload.

  1. <httpRuntime executionTimeout="3600" maxRequestLength="104857600" enable="true" />  
  2.   
  3. <system.webServer>  
  4.     <security>  
  5.       <requestFiltering>  
  6.         <requestLimits maxAllowedContentLength="104857600" />  
  7.       </requestFiltering>  
  8.     </security>  
  9.   </system.webServer>   

Step 4

Right-click on project Add select New Folder, name it VideoFileUpload to upload all the audio files in that folder. 

Step 5

Right-click on Models folder, select Add, then select Class.

Screenshot for creating model class 1

 

A window will appear. Choose Class, give it the name VideoFiles, then click on Add.

Screenshot for creating model class 2

 

Write class field and property as we have in the database table.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcUploadVideoFile_Demo.Models  
  7. {  
  8.     public class VideoFiles  
  9.     {  
  10.         public int ID { get; set; }  
  11.         public string Name { get; set; }  
  12.         public Nullable<int> FileSize { get; set; }  
  13.         public string FilePath { get; set; }  
  14.     }  
  15. }  

Step 6

Right-click on Controllers folder, select Add, then select Controller.  HomeController.

Screenshot for creating controller 1

After clicking on controller a window will appear; choose MVC 5 Controller-Empty and click on Add.

Screenshot for creating controller 2

 

After that, another window will appear with DefaultController. Remember, don’t change the suffix name of controller here. Click on Add and a Home controller will be added in Controllers folder.

Screenshot for creating controller 3

 

Add the following namespace

  1. using MvcUploadVideoFile_Demo.Models;  
  2. using System.Configuration;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.IO;  

Create UploadVideo action method with [HttpGet] in controller. Write the following code to retrieve the data from the database table.

  1. [HttpGet]  
  2.    public ActionResult UploadVideo()  
  3.    {  
  4.        List<VideoFiles> videolist = new List<VideoFiles>();  
  5.        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  6.        using (SqlConnection con = new SqlConnection(CS))  
  7.        {  
  8.            SqlCommand cmd = new SqlCommand("spGetAllVideoFile", con);  
  9.            cmd.CommandType = CommandType.StoredProcedure;  
  10.            con.Open();  
  11.            SqlDataReader rdr = cmd.ExecuteReader();  
  12.            while (rdr.Read())  
  13.            {  
  14.                VideoFiles video = new VideoFiles();                 
  15.                video.ID = Convert.ToInt32(rdr["ID"]);  
  16.                video.Name = rdr["Name"].ToString();  
  17.                video.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  18.                video.FilePath = rdr["FilePath"].ToString();  
  19.   
  20.                videolist.Add(video);  
  21.            }  
  22.        }  
  23.        return View(videolist);  
  24.    }  

Create UploadVideo action method with [HttpPost] in controller. Write following code to insert data into database and upload file in VideoFileUpload folder of project.

  1. [HttpPost]  
  2. public ActionResult UploadVideo(HttpPostedFileBase fileupload)  
  3. {  
  4.     if (fileupload != null)  
  5.     {  
  6.         string fileName= Path.GetFileName(fileupload.FileName);                
  7.         int fileSize = fileupload.ContentLength;  
  8.         int Size = fileSize / 1000;  
  9.         fileupload.SaveAs(Server.MapPath("~/VideoFileUpload/" + fileName));  
  10.   
  11.         string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  12.         using (SqlConnection con = new SqlConnection(CS))  
  13.         {  
  14.             SqlCommand cmd = new SqlCommand("spAddNewVideoFile", con);  
  15.             cmd.CommandType = CommandType.StoredProcedure;  
  16.             con.Open();  
  17.             cmd.Parameters.AddWithValue("@Name",fileName);  
  18.             cmd.Parameters.AddWithValue("@FileSize", Size);  
  19.             cmd.Parameters.AddWithValue("FilePath""~/VideoFileUpload/" + fileName);  
  20.             cmd.ExecuteNonQuery();  
  21.         }  
  22.     }  
  23.     return RedirectToAction("UploadVideo");  
  24. }  

Complete HomeController code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.IO;  
  7. using System.Web;  
  8. using System.Web.Mvc;  
  9. using MvcUploadVideoFile_Demo.Models;  
  10.   
  11. namespace MvcUploadVideoFile_Demo.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         // GET: Home  
  16.         public ActionResult Index()  
  17.         {  
  18.             return View();  
  19.         }       
  20.         [HttpGet]  
  21.         public ActionResult UploadVideo()  
  22.         {  
  23.             List<VideoFiles> videolist = new List<VideoFiles>();  
  24.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  25.             using (SqlConnection con = new SqlConnection(CS))  
  26.             {  
  27.                 SqlCommand cmd = new SqlCommand("spGetAllVideoFile", con);  
  28.                 cmd.CommandType = CommandType.StoredProcedure;  
  29.                 con.Open();  
  30.                 SqlDataReader rdr = cmd.ExecuteReader();  
  31.                 while (rdr.Read())  
  32.                 {  
  33.                     VideoFiles video = new VideoFiles();                 
  34.                     video.ID = Convert.ToInt32(rdr["ID"]);  
  35.                     video.Name = rdr["Name"].ToString();  
  36.                     video.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  37.                     video.FilePath = rdr["FilePath"].ToString();  
  38.   
  39.                     videolist.Add(video);  
  40.                 }  
  41.             }  
  42.             return View(videolist);  
  43.         }  
  44.         [HttpPost]  
  45.         public ActionResult UploadVideo(HttpPostedFileBase fileupload)  
  46.         {  
  47.             if (fileupload != null)  
  48.             {  
  49.                 string fileName= Path.GetFileName(fileupload.FileName);                
  50.                 int fileSize = fileupload.ContentLength;  
  51.                 int Size = fileSize / 1000;  
  52.                 fileupload.SaveAs(Server.MapPath("~/VideoFileUpload/" + fileName));  
  53.   
  54.                 string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  55.                 using (SqlConnection con = new SqlConnection(CS))  
  56.                 {  
  57.                     SqlCommand cmd = new SqlCommand("spAddNewVideoFile", con);  
  58.                     cmd.CommandType = CommandType.StoredProcedure;  
  59.                     con.Open();  
  60.                     cmd.Parameters.AddWithValue("@Name",fileName);  
  61.                     cmd.Parameters.AddWithValue("@FileSize", Size);  
  62.                     cmd.Parameters.AddWithValue("FilePath""~/VideoFileUpload/" + fileName);  
  63.                     cmd.ExecuteNonQuery();  
  64.                 }  
  65.             }  
  66.             return RedirectToAction("UploadVideo");  
  67.         }  
  68.     }  
  69. }  

Step 7

Right click on UploadVideo action method and Add view (uncheck use a layout page). Click on Add.

 

Add the following jquery script and bootstrap file in head section of view page. Download or add package from NuGet Package Manager Click on Tools => NuGet Package Manager => Manage NuGet Package. Select Browse type bootstrap in search bar, and select and install similar jquery. All downloaded files will be in content and scripts.

Add the following styles and scripts in the head section.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  3. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  4. <script src="~/scripts/bootstrap.min.js"></script>  

Write the following style for video frame and title of video

  1. <style type="text/css">  
  2.         .video-frame {  
  3.             width: 100%;  
  4.             height: 195px;  
  5.             border: 4px solid #dc3545;  
  6.             box-shadow: 1px 2px 3px #dc3545;  
  7.             border-radius: 3px;  
  8.         }  
  9.         .title {  
  10.             font-weight: 500;  
  11.             font-size: 14px;  
  12.             text-align: center;  
  13.             margin-bottom: 10px;  
  14.             margin-top: 10px;  
  15.             background-color: #dc3545;  
  16.             color: white;  
  17.             box-shadow: 1px 2px 4px #dc3545;  
  18.         }  
  19.     </style>  

Complete view code

  1. @{  
  2.     Layout = null;  
  3. }  
  4. <!DOCTYPE html>  
  5. <html>  
  6. <head>  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <title>Upload Video</title>  
  9.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  10.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  11.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  12.     <script src="~/scripts/bootstrap.min.js"></script>  
  13.     <style type="text/css">  
  14.         .video-frame {  
  15.             width: 100%;  
  16.             height: 195px;  
  17.             border: 4px solid #dc3545;  
  18.             box-shadow: 1px 2px 3px #dc3545;  
  19.             border-radius: 3px;  
  20.         }  
  21.         .title {  
  22.             font-weight: 500;  
  23.             font-size: 14px;  
  24.             text-align: center;  
  25.             margin-bottom: 10px;  
  26.             margin-top: 10px;  
  27.             background-color: #dc3545;  
  28.             color: white;  
  29.             box-shadow: 1px 2px 4px #dc3545;  
  30.         }  
  31.     </style>  
  32. </head>  
  33. <body>  
  34.     <div class="container py-4">  
  35.         <h3 class="text-center text-uppercase">How to Dynamically Upload and Play Video File Using ASP.NET MVC5</h3>  
  36.         <div class="card">  
  37.             <div class="card-header bg-danger text-white">  
  38.                 <h6 class="text-uppercase">video List</h6>  
  39.             </div>  
  40.             <div class="card-body">  
  41.                 <div class="row">  
  42.                     <button style="margin-left: 27px; margin-bottom:10px;" type="button" class="btn btn-danger rounded-0" data-toggle="modal" data-target="#UploadVideo">  
  43.                         <i class="fa fa-plus-circle"></i> Add New  
  44.                     </button>  
  45.                     <div class="modal fade" id="UploadVideo">  
  46.                         <div class="modal-dialog">  
  47.                             <div class="modal-content">  
  48.                                 <div class="modal-header">  
  49.                                     <h4 class="modal-title">Upload New video File</h4>  
  50.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  51.                                 </div>  
  52.                                 <div class="modal-body">  
  53.                                     @using (Html.BeginForm("UploadVideo""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  54.                                     {  
  55.                                         <div class="form-group">  
  56.                                             <label>Choose File:</label>  
  57.                                             <div class="input-group">  
  58.                                                 <div class="custom-file">  
  59.                                                     <input type="file" id="fileupload" name="fileupload" class="custom-file-input" />  
  60.                                                     <label class="custom-file-label"></label>  
  61.                                                 </div>  
  62.                                                 <div class="input-group-append">  
  63.                                                     <input type="submit" id="btnUpload" class="btn btn-secondary" value="Upload" />  
  64.                                                 </div>  
  65.                                             </div>  
  66.                                         </div>  
  67.                                     }  
  68.                                 </div>  
  69.                                 <div class="modal-footer">  
  70.                                     <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>  
  71.                                 </div>  
  72.                             </div>  
  73.                         </div>  
  74.                     </div>  
  75.                 </div>  
  76.                 <div class="row">  
  77.                     @foreach (var item in Model)  
  78.                     {  
  79.                         <div class="col-sm-4 col-md-4 col-xs-12">  
  80.                             <div class="title">@item.Name</div>  
  81.                             <div class="video-frame">  
  82.                                 <video style="width:100%; height:auto;" controls>  
  83.                                     <source src="@Url.Content(@item.FilePath)" type="video/mp4" />  
  84.                                 </video>  
  85.                             </div>  
  86.                         </div>  
  87.                     }  
  88.                 </div>  
  89.             </div>  
  90.         </div>  
  91.     </div>  
  92. </body>  
  93. </html>  

Step 8

Run Project ctr+F5

Screenshot 1

 

Screenshot 2

Screenshot 3

No comments:

Post a Comment