我们在 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);
    }

使用 fiddler 嗅探,这些是实际发送的 header :
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 位)上。

有什么帮助吗?

最佳答案

代替

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


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

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

关于c# - 强制文件下载头,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10008628/

10-14 17:49
查看更多