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) Razor Pages.
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.
Razor PageModel (Code-Behind)
The PageModel consists of following Handler methods.
Handler method for handling GET operation
First, 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 is created having name Items.
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 IndexModel : PageModel
{
private IWebHostEnvironment Environment { get; set; }
public IndexModel(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public List<SelectListItem> Items { get; set; }
public void OnGet()
{
string path = Path.Combine(this.Environment.WebRootPath, "Files");
string[] files = Directory.GetFiles(path);
this.Items = new List<SelectListItem>();
foreach (string file in files)
{
this.Items.Add(new SelectListItem { Text = Path.GetFileName(file), Value = MimeUtility.GetMimeMapping(file) });
}
}
}
Razor Page (HTML)
HTML Markup
The
HTML of Razor Page 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.
@page
@model Audio_Video_Server_Core_Razor.Pages.IndexModel
@{
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.Items)
{
<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