In this article I will explain with an example, how to play
Audio and
Video files from Server Folder (Directory) in ASP.Net Core (.Net Core 8) MVC.
Files Folder Location
The Audio and Video files are stored in the Files Folder (Directory) of the wwwroot Folder (Directory).
Namespaces
You will need to import the following namespace.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the path of the Folder (Directory) where the
Audio and
Video files are saved is fetched using
IWebHostEnvironment interface.
Then, the paths of the all Files are fetched from wwwroot Folder (Directory) and stored into a string Array using the GetFiles method of the Directory class.
Then, a new object of Generic List collection of SelectListItem class is defined.
Finally, a FOR EACH loop is executed over the selected files and each file is added to the Generic List collection of SelectListItem class with FileName and MIME type of the file.
public class HomeController : Controller
{
public IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public IActionResult Index()
{
string path = Path.Combine(this.Environment.WebRootPath, "Files");
string[] files = Directory.GetFiles(path);
List<SelectListItem> items = new List<SelectListItem>();
foreach (string file in files)
{
items.Add(new SelectListItem { Text = Path.GetFileName(file), Value = MimeUtility.GetMimeMapping(file) });
}
return View(items);
}
}
View
HTML Markup
Inside the View, the Generic List collection of SelectListItem is declared as model for the View.
The View consists of an
HTML Table.
The Table consists of an
HTML5 Audio and
Video element.
Note: I am making use of
HTML5 Audio Player to play the audios and
HTML5 Video Player to play the videos on the web page.
Inside the Table, a FOR EACH loop is executed over the Model and a check is performed whether the File is
Audio or
Video using MIME type of file.
Finally, based on the File type the source is set to the appropriate element i.e.
HTML5 Audio or
Video.
@model List<SelectListItem>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table>
<tr>
<th>File Name</th>
<th></th>
</tr>
@foreach (SelectListItem item in Model)
{
<tr>
<td>@item.Text</td>
<td>
@if (item.Value.StartsWith("audio/"))
{
<audio controls="controls">
<source src="/Files/@item.Text" type='audio/mpeg' />
</audio>
}
@if (item.Value.StartsWith("video/"))
{
<video src="/Files/@item.Text" controls="controls" width="300" />
}
</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads