views:

604

answers:

7

Hello,

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';
        this.Response.AddHeader("Content-Disposition", "test.mp3");
        this.Response.ContentType = "audio/mpeg";

        return View();
    }

But how do I return the mp3 file?

thanks

A: 

You should create your own class which inherits from ActionResult, here is an example of serving an image.

Yuriy Faktorovich
A: 

If your MP3 file is in a location accessible to users (i.e. on a website folder somewhere) you could simply redirect to the mp3 file. Use the Redirect() method on the controller to accomplish this:

public ActionResult Stream()
{
    return Redirect("test.mp3");
}
Ryan Brunner
+1  A: 

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" };
}
Joseph
+3  A: 

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[].

Carles
+1  A: 

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.

Stief Dirckx
A: 

Hi guys! 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") %>
Laurel.Wu
A: 
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"));

        }
ta4ka