3

我们在 ASP.NET 服务器上提供文件时遇到了一个奇怪的问题。

如果用户单击链接,我们希望有一个文件下载对话框。没有为 WMV 打开 WMP,没有为 PDF 打开 Adob​​e,等等。

为了强制执行此操作,我们使用以下 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);
    }

用提琴手嗅探,这些是发送的实际标头:

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,对于 Adob​​e Reader 也是如此,它仍然会在 IE 窗口中打开 Adob​​e Reader。

此问题似乎不会在 Firefox 上发生,但它会在 Windows 7(32 位)上的 IE8(32 位)上发生。

有什么帮助吗?

4

1 回答 1

5

代替

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

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

看看它做了什么,但不知道它是否适用于所有浏览器。

于 2012-04-04T09:47:17.630 回答