How to Transfer MP3 Using ASP.NET MVC Controller Action

I have an mp3 file on my site. I want to bring it out as a representation. 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 can I return an mp3 file?

+4
source share
7 answers

Create an action as follows:

 public ActionResult Stream(string mp3){ byte[] file=readFile(mp3); return File(file,"audio/mpeg"); } 

The readFile function should read MP3 from the file and return it as byte [].

+9
source

You should return FileResult instead of ViewResult:

  return File(stream.ToArray(), "audio/mpeg", "test.mp3"); 

The stream parameter must be a file or storage file from an mp3 file.

+3
source

If your MP3 file is located in a place accessible to the user (for example, in the website folder), you can simply redirect it to an mp3 file. Use the Redirect () method on the controller to do the following:

 public ActionResult Stream() { return Redirect("test.mp3"); } 
+2
source

You do not want to create a presentation, you want to return the mp3 file as your ActionResult.

Phil Haack did an ActionResult to do this by calling DownloadResult. Here is the article .

The resulting syntax will look something like this:

 public ActionResult Download() { return new DownloadResult { VirtualPath="~/content/mysong.mp3", FileDownloadName = "MySong.mp3" }; } 
+1
source
 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")); } 
+1
source

You must create your own class that inherits from ActionResult, here is an example of image servicing.

0
source

Why not use Filepathresult?

Like this:

  public FilePathResult DownLoad() { return new FilePathResult(Url.Content(@"/Content/01.I Have A Dream 4'02.mp3"), "audio/mp3"); } 

And create a download link:

 <%=Html.ActionLink("Download the mp3","DownLoad","home") %> 
0
source

All Articles