Asp.net Core Dynamically Create a File Upload

Introduction

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

Pace 1

Create a database in the SQL Server of your choice.

  1. CREATE TABLE  [dbo].[VideoFiles](
  2.     [ID] [int ] IDENTITY(ane,1) NOT NULL ,
  3.     [Name ] [nvarchar](50) Cypher ,
  4.     [FileSize] [int ] Zilch ,
  5.     [FilePath] [nvarchar](100)NULL ,
  6. CONSTRAINT  [PK_VideoFiles] Chief Primal  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. GO
  12. CREATE process  [dbo].[spAddNewVideoFile]
  13. (
  14. @Name  nvarchar(50),
  15. @FileSizeint ,
  16. @FilePath nvarchar(100)
  17. )
  18. as
  19. begin
  20. insert into  VideoFiles ( Name ,FileSize,FilePath)
  21. values  (@ Name ,@FileSize,@FilePath)
  22. end
  23. CREATE procedure  [dbo].[spGetAllVideoFile]
  24. as
  25. begin
  26. select  ID, Proper noun ,FileSize,FilePath from  VideoFiles
  27. end

Step ii

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

Screenshot one

ASP.NET

Choose empty from ASP.Internet Templates, select checkbox MVC, and click on OK, every bit shown in the image below.

Screenshot two

Step 3

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

  1. <connectionStrings>
  2.     <add proper noun="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= "truthful"  />
  2. <organisation.webServer>
  3.     <security>
  4.       <requestFiltering>
  5.         <requestLimits maxAllowedContentLength="104857600"  />
  6.       </requestFiltering>
  7.     </security>
  8. </system.webServer>

Stride 4

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

Step 5Right-click on Models binder, select Add, so select Class.

Screenshot for creating model class one

A window will announced. Cull Form, give information technology the proper noun VideoFiles, then click on Add.

Screenshot for creating model class 2

Write grade field and belongings as we have in the database table.

  1. using  Organization;
  2. using  System.Collections.Generic;
  3. using  Organization.Linq;
  4. using  System.Spider web;
  5. namespace  MvcUploadVideoFile_Demo.Models
  6. {
  7. public class  VideoFiles
  8.     {
  9. public int  ID { become ; ready ; }
  10. public string  Proper name { become ; set ; }
  11. public  Nullable< int > FileSize { become ; prepare ; }
  12. public string  FilePath { become ; set ; }
  13.     }
  14. }

Step 6

Right-click on Controllers folder, select Add together, and so select Controller.  HomeController.

Screenshot for creating controller one

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

Screenshot for creating controller two

After that, some other window will appear with DefaultController. Call back, don't modify the suffix name of controller hither. Click on Add and a Home controller will be added in Controllers folder.

Screenshot for creating controller iii

Add the following namespace

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

Create UploadVideo activeness method with [HttpGet] in controller. Write the following code to recall 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 = Catechumen.ToInt32(rdr["ID" ]);
  16.                video.Proper name = rdr["Name" ].ToString();
  17.                video.FileSize = Convert.ToInt32(rdr["FileSize" ]);
  18.                video.FilePath = rdr["FilePath" ].ToString();
  19.                videolist.Add together(video);
  20.            }
  21.        }
  22. return  View(videolist);
  23.    }

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

  1. [HttpPost]
  2. public  ActionResult UploadVideo(HttpPostedFileBase fileupload)
  3. {
  4. if  (fileupload != nix )
  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.         string CS = ConfigurationManager.ConnectionStrings["DBCS" ].ConnectionString;
  11.         using (SqlConnection con =new  SqlConnection(CS))
  12.         {
  13.             SqlCommand cmd =new  SqlCommand( "spAddNewVideoFile" , con);
  14.             cmd.CommandType = CommandType.StoredProcedure;
  15.             con.Open up();
  16.             cmd.Parameters.AddWithValue("@Proper name" ,fileName);
  17.             cmd.Parameters.AddWithValue("@FileSize" , Size);
  18.             cmd.Parameters.AddWithValue("FilePath" , "~/VideoFileUpload/"  + fileName);
  19.             cmd.ExecuteNonQuery();
  20.         }
  21.     }
  22. return  RedirectToAction( "UploadVideo" );
  23. }

Complete HomeController lawmaking

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

Pace vii

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

Add the post-obit jquery script and bootstrap file in caput section of view page. Download or add package from NuGet Bundle Manager Click on Tools => NuGet Package Manager => Manage NuGet Bundle. Select Browse type bootstrap in search bar, and select and install like 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-crawly.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 championship of video

  1. <way blazon= "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-marshal : eye ;
  13. margin-bottom : 10px ;
  14. margin-height : 10px ;
  15. background-color : #dc3545 ;
  16. color : white ;
  17.             box-shadow:1px 2px 4px #dc3545 ;
  18.         }
  19. </style>

Complete view lawmaking

  1. @{
  2.     Layout =null ;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <caput>
  7.     <meta name="viewport"  content= "width=device-width"  />
  8.     <title>Upload Video</championship>
  9.     <link rel="stylesheet"  href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/iv.7.0/css/font-crawly.min.css" >
  10.     <link href="~/Content/bootstrap.min.css"  rel= "stylesheet"  />
  11.     <script src="~/scripts/jquery-3.three.ane.min.js" ></script>
  12.     <script src="~/scripts/bootstrap.min.js" ></script>
  13.     <style type="text/css" >
  14.         .video-frame {
  15.             width: 100%;
  16.             pinnacle: 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.             colour: white;
  29.             box-shadow: 1px 2px 4px #dc3545;
  30.         }
  31.     </style>
  32. </head>
  33. <torso>
  34.     <divgrade = "container py-4" >
  35.         <h3class = "text-center text-majuscule" >How to Dynamically Upload and Play Video File Using ASP.NET MVC5</h3>
  36.         <divcourse = "card" >
  37.             <divclass = "card-header bg-danger text-white" >
  38.                 <h6class = "text-capital letter" >video List</h6>
  39.             </div>
  40.             <divform = "card-body" >
  41.                 <divclass = "row" >
  42.                     <button fashion="margin-left: 27px; margin-bottom:10px;"  blazon= "push" class = "btn btn-danger rounded-0"  information-toggle= "modal"  information-target= "#UploadVideo" >
  43.                         <iclass = "fa fa-plus-circle" ></i> Add New
  44.                     </button>
  45.                     <divcourse = "modal fade"  id= "UploadVideo" >
  46.                         <divclass = "modal-dialog" >
  47.                             <divclass = "modal-content" >
  48.                                 <divcourse = "modal-header" >
  49.                                     <h4class = "modal-title" >Upload New video File</h4>
  50.                                     <button type="push" class = "close"  information-dismiss= "modal" >×</push>
  51.                                 </div>
  52.                                 <divclass = "modal-body" >
  53.                                     @using (Html.BeginForm("UploadVideo" , "Habitation" , FormMethod.Mail, new  { enctype = "multipart/grade-information"  }))
  54.                                     {
  55.                                         <divform = "class-group" >
  56.                                             <label>Cull File:</label>
  57.                                             <divform = "input-group" >
  58.                                                 <divclass = "custom-file" >
  59.                                                     <input blazon="file"  id= "fileupload"  name= "fileupload" course = "custom-file-input"  />
  60.                                                     <labelclass = "custom-file-label" ></label>
  61.                                                 </div>
  62.                                                 <divgrade = "input-group-append" >
  63.                                                     <input blazon="submit"  id= "btnUpload" class = "btn btn-secondary"  value= "Upload"  />
  64.                                                 </div>
  65.                                             </div>
  66.                                         </div>
  67.                                     }
  68.                                 </div>
  69.                                 <divclass = "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.                 <divclass = "row" >
  77.                     @foreach (var  detail in  Model)
  78.                     {
  79.                         <divclass = "col-sm-4 col-doctor-four col-xs-12" >
  80.                             <divclass = "championship" >@item.Name</div>
  81.                             <divclass = "video-frame" >
  82.                                 <video fashion="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. </torso>
  93. </html>

Step 8

Run Projection ctr+F5

Screenshot one

Screenshot two

Screenshot 3

Conclusion

In this article, I have explained how to upload and play a video file of up to 100MB in size using ASP.NET MVC5. I accept used bootstrap 4. I have explained a step by pace procedure with some screenshots.

daileyfroprithe.blogspot.com

Source: https://www.c-sharpcorner.com/article/how-to-dynamically-upload-and-play-video-file-using-asp-net-mvc-5/

0 Response to "Asp.net Core Dynamically Create a File Upload"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel