强制文件下载头部

4
我们在ASP.NET服务器上提供文件时遇到了奇怪的问题。
如果用户单击链接,我们希望出现文件下载对话框。WMV不会打开WMP,PDF也不会打开Adobe等。
为了强制实现这一点,我们使用以下HTTP处理程序来处理WMV、PDF等文件。
    public void ProcessRequest(HttpContext context)
    {
        // don't allow caching
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        context.Response.Cache.SetNoStore();
        context.Response.Cache.SetExpires(DateTime.MinValue);

        string contentDisposition = string.Format("attachment; filename=\"{0}\"", Path.GetFileName(context.Request.PhysicalPath));
        string contentLength;

        using (FileStream fileStream = File.OpenRead(context.Request.PhysicalPath))
        {
            contentLength = fileStream.Length.ToString(CultureInfo.InvariantCulture);
        }

        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", contentDisposition);
        context.Response.AddHeader("Content-Length", contentLength);
        context.Response.AddHeader("Content-Description", "File Transfer");
        context.Response.AddHeader("Content-Transfer-Encoding", "binary");
        context.Response.TransmitFile(context.Request.PhysicalPath);
    }

使用Fiddler进行抓包,以下是实际发送的头部信息:

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Length: 8661299
Content-Type: application/octet-stream
Expires: -1
Server: Microsoft-IIS/7.5
Content-Disposition: attachment; filename="foo.wmv"
Content-Description: File Transfer
Content-Transfer-Encoding: binary
X-Powered-By: ASP.NET
Date: Wed, 04 Apr 2012 09:38:14 GMT

然而,当我们点击WMV链接时,这仍会打开WMP,同样的情况也会发生在Adobe Reader上,在IE窗口内打开Adobe Reader。

这个问题似乎没有出现在Firefox上,但是在Windows 7(32位)上的IE8(32位)上会出现这个问题。

需要帮助吗?


你尝试设置Content-Type为audio/x-ms-wmv来处理WMV文件了吗?而且据我所知,你不需要在文件名周围加双引号... - Roy Dictus
我确实需要双引号,否则Firefox在文件名中包含空格时无法理解。 - Snake
真的,但在你的例子中文件名中没有空格... - Roy Dictus
1个回答

6
替换
context.Response.ContentType = "application/octet-stream";

使用

context.Response.ContentType = "application/force-download";

看看它的效果,不确定是否适用于所有浏览器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接