gpt4 book ai didi

c# - 强制文件下载头

转载 作者:行者123 更新时间:2023-11-30 15:04:38 26 4
gpt4 key购买 nike

我们在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com