How to stream an MP3 from an ASP.NET MVC Controller Action

柔情痞子 提交于 2019-12-18 12:08:45

问题


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?


回答1:


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




回答2:


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.




回答3:


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");
}



回答4:


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" };
}



回答5:


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"));

        }



回答6:


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




回答7:


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") %>


来源:https://stackoverflow.com/questions/1643737/how-to-stream-an-mp3-from-an-asp-net-mvc-controller-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!