I have an mp3 file in my site. I want to output it as a view. In my controller I have:
public ActionResult Stream()
{
string file = \'test.mp3\';
You should return a FileResult instead of a ViewResult:
return File(stream.ToArray(), "audio/mpeg", "test.mp3");
The stream parameter should be a filestream or memorystream from the mp3 file.
Create an Action like this:
public ActionResult Stream(string mp3){
byte[] file=readFile(mp3);
return File(file,"audio/mpeg");
}
The function readFile should read the MP3 from the file and return it as a byte[].
You don't want to create a view, you want to return the mp3 file as your ActionResult.
Phil Haack made an ActionResult to do just this, called a DownloadResult. Here's the article.
The resulting syntax would look something like this:
public ActionResult Download()
{
return new DownloadResult
{ VirtualPath="~/content/mysong.mp3", FileDownloadName = "MySong.mp3" };
}
public FileResult Download(Guid mp3FileID)
{
string mp3Url = DataContext.GetMp3UrlByID(mp3FileID);
WebClient urlGrabber = new WebClient();
byte[] data = urlGrabber.DownloadData(mp3Url);
FileStream fileStream = new FileStream("ilovethismusic.mp3", FileMode.Open);
fileStream.Write(data, 0, data.Length);
fileStream.Seek(0, SeekOrigin.Begin);
return (new FileStreamResult(fileStream, "audio/mpeg"));
//return (new FileContentResult(data, "audio/mpeg"));
}
You should create your own class which inherits from ActionResult, here is an example of serving an image.
Why not use the Filepathresult?
Like this :
public FilePathResult DownLoad()
{
return new FilePathResult(Url.Content(@"/Content/01.I Have A Dream 4'02.mp3"), "audio/mp3");
}
And create the download link:
<%=Html.ActionLink("Download the mp3","DownLoad","home") %>