2014-10-12 165 views
0

我有一個PDF文件的href鏈接,點擊後它會在瀏覽器的新頁面中打開。我希望這下載,而不是在新標籤中打開。單擊時下載PDF(不在瀏覽器中打開)

那麼如何使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(); 
    } 
} 
+0

你可以發佈一些示例url到你正在顯示的PDF文件嗎? – Michael 2014-10-12 10:15:07

+0

點擊後,它會在新標籤中指向類似內容:http:// localhost:52747/PDF/CSS%20Quick%20Syntax%20Reference.pdf – user123456 2014-10-12 10:20:30

回答

2

屬性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

+0

這不是HTML5屬性嗎? – Michael 2014-10-12 10:24:31

+0

@michaelmoore,是的,http://www.w3schools.com/tags/att_a_download.asp – 2014-10-12 10:26:26

+0

然後我會建議在你的答案中提到它,因爲可能OP需要支持'html5'不兼容的瀏覽器。 – Michael 2014-10-12 10:28:09

0
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(); 

類似的問題已經被問here

相關問題