Introduction
This article demonstrates how to upload an audio file up to 50MB and play dynamically using ASP.NET MVC 5. I will upload the audio file in my project folder (AudioFileUpload) and its path in SQL Server database table.
I will retrieve (display) all the uploaded audio files and their related data in HTML table with sorting, searching, and paging functionality using Bootstrap 4 and jQuery data table plugin. We will understand this step by step.
Step 1
Create a database in SQL Server of your choice.
- CREATE TABLE [dbo].[AudioFiles](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [FileSize] [int] NULL,
- [FilePath] [nvarchar](100) NULL,
- CONSTRAINT [PK_AudioFiles] 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]
-
- GO
-
- CREATE procedure [dbo].[spAddNewAudioFile]
- (
- @Name nvarchar(50),
- @FileSize int,
- @FilePath nvarchar(100)
- )
- as
- begin
- insert into AudioFiles (Name,FileSize,FilePath)
- values (@Name,@FileSize,@FilePath)
- end
-
- CREATE procedure [dbo].[spGetAllAudioFile]
- as
- begin
- select ID,Name,FileSize,FilePath from AudioFiles
- end
Step 2
Create an empty ASP.NET Web Application project in Visual Studio 2015. As shown in the below screenshot, open Visual Studio ( VS 2015 in my case). Click on the new project, choose web template >> choose ASP.NET Web Application, and give it a meaningful name. Then, click OK.
Choose empty from ASP.NET Templates, select checkbox MVC, and click on OK.
Step 3
Double click and open webconfig file to add the database connection.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=MvcDemo; integrated security=true;" />
- </connectionStrings>
Add this below code in webconfig file to allow 50MB file to upload.
- <httpRuntime executionTimeout="3600" maxRequestLength="51200" enable="true" />
-
- <system.webServer>
- <security>
- <requestFiltering>
- <requestLimits maxAllowedContentLength="104857600" />
- </requestFiltering>
- </security>
- </system.webServer>
Step 4
Right-click on the project, add New Folder, name it AudioFileUpload to upload all audio files in that folder.
Step 5
Right click on Models folder, select Add >> Class.
Screenshot for creating model class-1
A window will appear. Choose Class, give it a name as AudioFile, then click on Add.
Screenshot for creating model class-2
Write class field and property as we have in the database table.
- using System;
-
- namespace MvcUploadAudioFile_Demo.Model
- {
- public class AudioFile
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public Nullable<int> FileSize { get; set; }
- public string FilePath { get; set; }
- }
- }
Step 6
Right-click on Controllers folder, select Add >> Controller. Name it as 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 highlighted by default. Change the default to HomeController. Remember, don’t change suffix name of the Controller here. Click on Add and the Home controller will be added to the Controllers folder.
Screenshot for creating controller 3
Add the following namespace in Controller class
- using MvcUploadAudioFile_Demo.Model;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.IO;
Create UploadAudio action method with [HttpGet] in controller. Write the following code to retrieve the data from database table.
- [HttpGet]
- public ActionResult UploadAudio()
- {
- List<AudioFile> audiolist = new List<AudioFile>();
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllAudioFile", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- AudioFile audio = new AudioFile();
- audio.ID = Convert.ToInt32(rdr["ID"]);
- audio.Name = rdr["Name"].ToString();
- audio.FileSize = Convert.ToInt32(rdr["FileSize"]);
- audio.FilePath = rdr["FilePath"].ToString();
-
- audiolist.Add(audio);
- }
- }
- return View(audiolist);
- }
Create UploadAudio action method with [HttpPost] in controller. Write the following code to insert data into database and upload file in AudioFileUpload folder of project.
- [HttpPost]
- public ActionResult UploadAudio(HttpPostedFileBase fileupload)
- {
- if (fileupload != null)
- {
- string fileName = Path.GetFileName(fileupload.FileName);
- int fileSize = fileupload.ContentLength;
- int Size = fileSize/1000000;
- fileupload.SaveAs(Server.MapPath("~/AudioFileUpload/" + fileName));
-
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewAudioFile", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", fileName);
- cmd.Parameters.AddWithValue("@FileSize", Size);
- cmd.Parameters.AddWithValue("FilePath", "~/AudioFileUpload/" + fileName);
- cmd.ExecuteNonQuery();
- }
- }
- return RedirectToAction("UploadAudio");
- }
Complete code for HomeController to insert and retrieve file.
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.Mvc;
- using MvcUploadAudioFile_Demo.Model;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.IO;
-
- namespace MvcUploadAudioFile_Demo.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- [HttpGet]
- public ActionResult UploadAudio()
- {
- List<AudioFile> audiolist = new List<AudioFile>();
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllAudioFile", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- AudioFile audio = new AudioFile();
- audio.ID = Convert.ToInt32(rdr["ID"]);
- audio.Name = rdr["Name"].ToString();
- audio.FileSize = Convert.ToInt32(rdr["FileSize"]);
- audio.FilePath = rdr["FilePath"].ToString();
-
- audiolist.Add(audio);
- }
- }
- return View(audiolist);
- }
- [HttpPost]
- public ActionResult UploadAudio(HttpPostedFileBase fileupload)
- {
- if (fileupload != null)
- {
- string fileName = Path.GetFileName(fileupload.FileName);
- int fileSize = fileupload.ContentLength;
- int Size = fileSize/1000000;
- fileupload.SaveAs(Server.MapPath("~/AudioFileUpload/" + fileName));
-
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewAudioFile", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", fileName);
- cmd.Parameters.AddWithValue("@FileSize", Size);
- cmd.Parameters.AddWithValue("FilePath", "~/AudioFileUpload/" + fileName);
- cmd.ExecuteNonQuery();
- }
- }
- return RedirectToAction("UploadAudio");
- }
- }
- }
Step 7
Right-click on UploadAudio action method and Add View (uncheck use a layout page). Click on Add.
Add the following jQuery script and bootstrap file in the head section of the View page. Download or add package from NuGet Package Manager, click on Tools => NuGet Package Manager => Manage NuGet Package for the solution.
Select Browse, type bootstrap in search bar, select and install similar jQuery. All downloaded files will be in Content and scripts.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
- <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
- <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
Write the below jQuery script to avoid playing all audios at the same time. This script will allow you to play one audio at a time and pause others when you play an audio.
- <script type="text/javascript" >
- $(document).ready(function () {
- $('#dataTable').DataTable();
-
- $("audio").on("play", function () {
- $("audio").not(this).each(function (index, audio) {
- audio.pause();
- });
- });
- });
- </script>
Design of the complete HTML page in UploadAudio View.
Step 8
Run the project by pressing Ctr+F5.
Screenshot 1
Screenshot 2
Screenshot 3
Conclusion
In this article, I have explained how to upload and play audio files up to 50MB in size using ASP.NET MVC5. I have used Bootstrap 4 and jQuery datatable plugin for searching, shorting and paging.