mp3 文件无法下载?

mp3 files not getting downloaded?

我用c#写了下面几行代码

 private void DownloadFile(byte[] myData, string Name)
    {
        Response.Expires = 0;
        Response.Clear();
        string ext= System.IO.Path.GetExtension(Name);
        switch(ext)
        {
            case ".mp3":
                 Response.ContentType = "audio/mpeg";
                break;
            default:
            Response.ContentType = "Application/octet-stream";
            break;
        }
        Response.AddHeader("content-length", myData.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Name);
        try
        {
            Response.BinaryWrite(myData);
        }
        catch { }
        Response.Flush();
        Response.End();
    }

现在的问题是,我们点击下载mp3文件的时候,是直接播放的。我希望它应该下载它。我也想下载所有类型的文件。

你所拥有的应该就足够了,假设你添加的headers在传输过程中没有被剥离/损坏(通过Fiddler或类似工具很容易检查) .

由于您不希望浏览器解释此数据,实用的选择可能是简单地将所有数据作为 "application/octet-stream" 发送,而不考虑内容。虽然 "attachment" 处理应该足以满足此要求,但 RFC 2616、19.5.1 ("Content-Disposition"):

中明确调用了此方法

If this header is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.

我为此纠结了最长时间,但终于解决了这个难题。使用 Response.WriteFile。您可以使用 Response.Flush 跟随它,但我发现这是不必要的。 .mp3 文件不需要额外的 headers。在我的例子中,.mp3 文件位于根目录下的一个文件夹中。还有一个好处:使 .mp3 下载在智能手机上运行的关键要素(这是我的困境)使用 Response.End,并通过发回 Response.StatusCode 告诉移动设备下载已完成= 200.

string FilenameMP3 = "~/someFolder/xyz.mp3";
string headerFilename = Filename.Substring(Filename.IndexOf("/") + 1);
Response.AppendHeader("Content-Disposition", String.Concat("attachment;filename=\"", headerFilename, "\""));
Response.ContentType = "audio/mpeg";
try
{
    Response.WriteFile(Filename, true);
    Response.End();
}
finally
{
     Response.StatusCode = 200;
     Response.Close();
}