除非您将 Content-Disposition 标头添加到响应中,否则您不能仅从超链接(或可靠地使用 Javascript)强制下载文件;因此,解决此问题并始终强制下载文件的一种方法可能是拥有一个中间页面,该页面将为您添加标题。
因此,您的链接必须变成这样:
<a href="DownloadMgr.aspx?File=brochure.pdf" target="_blank">Download Brochure</a>
DownloadMgr.aspx
应该是这样的:
if(!IsPostback)
{
if(Request.QueryString["File"]!=null)
{
if(Request.QueryString["File"].Contains("pdf")))
Response.ContentType = "application/pdf"; //varies depending on the file being streamed
Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString["File"]);
Response.WriteFile(Server.MapPath(Request.QueryString["File"]));
}
不过,更好的方法是创建一个 HTTPHandler 来做同样的事情。您可以查看此答案以获取有关如何执行此操作的更多详细信息。创建 HTTPHandler 的好处之一是它不涉及常规aspx
页面所需的所有处理、初始化等。
完整代码示例:
<%@ Language=C# %>
<HTML>
<head>
<title>Download Manager</title>
</head>
<script runat="server" language="C#">
void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
if (Request.QueryString["File"] != null)
{
if (Request.QueryString["File"].Contains("pdf"))
Response.ContentType = "application/pdf"; //varies depending on the file being streamed
Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString["File"]);
Response.WriteFile(Server.MapPath(Request.QueryString["File"]));
}
}
}
</script>
<body>
<form id="form" runat="server">
</form>
</body>
</HTML>
VB.NET版
<%@ Language="VB" %>
<HTML>
<head>
<title>Download Manager</title>
</head>
<script runat="server" language="VB">
Sub Page_Load()
If (Not Page.IsPostBack) Then
If (Request.QueryString("File") IsNot Nothing) Then
If (Request.QueryString("File").Contains("pdf")) Then
Response.ContentType = "application/pdf" 'varies depending on the file being streamed
End If
Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString("File"))
Response.WriteFile(Server.MapPath(Request.QueryString("File")))
End If
End If
End Sub
</script>
<body>
<form id="form" runat="server">
</form>
</body>
</HTML>
现在将上面的代码另存为DownloadMgr.aspx
并将其放入您的网站。