Reputation: 381
I currently have an HTML page that contains a link:
<a href="javascript:void()" onclick="return getAudioFile('fileLocation');">Listen</a>
Clicking the "Listen" link calls this function:
function getRecordingFile(fileLocation) {
};
Which should ultimately call this controller method:
[HttpPost]
public ActionResult GetAudioFile(string fileLocation)
{
return null;
}
I have emptied out the function and method because I have tried several different things to accomplish this: I need to access an audio file from a local location and allow the user to listen to it/download it upon clicking the Listen
link.
What seems to be the best way to go about this?
Upvotes: 3
Views: 5939
Reputation: 385
Other answers don't enable Partial Content so a user can't seek.
Before proceeding, you should also ensure that an attacker can't traverse the filesystem by providing ../../file
or similar as a path
[HttpGet]
public ActionResult GetAudioFile(string fileLocation)
{
using var fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read);
using var br = new BinaryReader(fs);
long numBytes = new FileInfo(fileLocation).Length;
var buff = br.ReadBytes((int)numBytes);
var fileResult = File(buff, "audio/mpeg", "callrecording.mp3");
fileResult.EnableRangeProcessing = true;
return fileResult;
}
Upvotes: 0
Reputation: 381
Here is the final result:
[HttpGet]
public ActionResult GetAudioFile(string fileLocation)
{
var bytes = new byte[0];
using (var fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read)
{
var br = new BinaryReader(fs);
long numBytes = new FileInfo(fileLocation).Length;
buff = br.ReadBytes((int)numBytes);
}
return File(buff, "audio/mpeg", "callrecording.mp3");
}
On the page, the link is:
<a href="/Controller/GetAudioFile?fileName=@fileLocation">Listen</a>
Kudos to my boss for the help.
Upvotes: 1
Reputation: 882
Use a FileResult perhaps?
[HttpPost]
public FileResult GetAudioFile(string fileLocation)
{
using(FileStream fs = new FileStream(fileLocation)){
return File(fs.ToArray(), "audio/mpeg");
}
}
Upvotes: 0