单击时下载PDF(不在浏览器中打开)

本文关键字:浏览器 下载 PDF 单击 | 更新日期: 2023-09-27 18:26:23

我有一个指向PDF文件的href链接,单击后会在浏览器的新页面中打开。我想下载这个,而不是在新的选项卡中打开。

那么,如何使PDF文件链接可下载,而不是在浏览器中打开它们呢?

这是代码:

<asp:FormView ID="FormView2" runat="server">
            <ItemTemplate>
                <asp:LoginView ID="LoginView1" runat="server">
                    <LoggedInTemplate>
                          <asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank"></asp:HyperLink>
                        <br />
                    </LoggedInTemplate>
                    <AnonymousTemplate>
                            <p>You need to log in to view the book.</p>
                    </AnonymousTemplate>
                </asp:LoginView>
            </ItemTemplate>
        </asp:FormView>

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    int bookId = Convert.ToInt32(Request.QueryString.Get("BookId"));

    using (LibraryEntities entities = new LibraryEntities())
    {
        var book = (from r in entities.Books
                          where r.Id == bookId
                          select r);
        FormView2.DataSource = book;
        FormView2.DataBind();
    }
}

单击时下载PDF(不在浏览器中打开)

只需将属性download添加到<asp:HyperLink>即可。

最终代码为.

<asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" 
               NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank" download
</asp:HyperLink>

注意:这是HTML5属性,因此它仅适用于兼容HTML5的浏览器。检查此链接以查看不同浏览器上对download属性的支持-http://caniuse.com/#feat=download

Response.Clear(); //eliminates issues where some response has already been sent
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.sql", filename));
Response.Write(yourSQL);
Response.End();

这里也提出了类似的问题。