mp3文件没有下载?

时间:2015-03-26 09:09:13

标签: c# asp.net c#-4.0 mime-types

我在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文件下载时,都会直接播放。我希望它应该下载它。我还想要下载所有类型的文件。

2 个答案:

答案 0 :(得分:0)

由于您不希望浏览器解释此数据,因此实用选项可能只是将所有数据作为“application / octet-stream”发送,而不管内容如何。虽然“附件”处理应该足够,但这种方法在RFC 2616,19.5.1(“内容处置”)中明确提出:

  

如果在带有application / octet-stream内容类型的响应中使用此标头,则隐含的建议是用户代理不应显示响应,而是直接输入“save response as ...”对话框。

答案 1 :(得分:0)

我在这方面挣扎的时间最长,但终于解决了这个难题。使用Response.WriteFile。您可以使用Response.Flush跟随它,但我发现这是不必要的。 .mp3文件不需要额外的标头。在我的例子中,.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();
}
相关问题