In this article I will explain with an example, how to save BYTE Array to audio file (MP3) in ASP.Net Core (.Net Core 8).
Audio File Location
The sample audio file (MP3) is located inside the Files Folder (Directory) of wwwroot Folder (Directory).
Controller
Inside the Controller, first the private property IWebHostEnvironment interface is created.
Then, the interface is injected into the Constructor (HomeController) using Dependency Injection method and the injected object is assigned to private property (created earlier).
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, first the path of the sample audio file (MP3) is determined using IWebHostEnvrionment interface.
Then, the BYTE Array of the sample audio file (MP3) is determined using ReadAllBytes method of the File class.
After that, the BYTE Array is saved to another audio file (MP3) using WriteAllBytes method of File class and the audio file (MP3) is created inside the Files Folder (Directory).
Finally, the success message is set into a
ViewBag object and the View is redirected
Index Action method.
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Save()
{
string path = Path.Combine(this.Environment.WebRootPath, "Files/");
// Converting the file to Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path + "Sample.mp3");
// Saving Byte Array to mp3.
System.IO.File.WriteAllBytes(path + "Welcome.mp3", bytes);
// Showing message.
ViewBag.Message = "File have been saved.";
return View("Index");
}
}
View
HTML Markup
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Save.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Button.
Submitting the Form
When the
Submit Button is clicked, the
ViewBag object is checked for NULL and if it is not NULL then the value of the
ViewBag object is displayed using
JavaScript Alert Message Box.
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Save">
<input id="btnSave" type="submit" value="Save" />
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads