2014-11-14 91 views
0

一切工作正常,直到PDF文件應該能夠點擊瀏覽器上查看。雖然下載鏈接工作完美。Gridview下載和查看pdf文件在asp.net和c#

我的網...

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded"> 
<Columns> 
    <asp:BoundField DataField="FileDate" HeaderText="Dated" /> 
    <asp:BoundField DataField="FileName" HeaderText="File Name" /> 
    <asp:TemplateField> 
     <ItemTemplate> 
      <asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("FilePath") %>' runat="server" OnClick = "DownloadFile" ></asp:LinkButton> 
      <asp:LinkButton ID="btnOpen" Text="View" Font-Bold="true" runat="server" onclick="btnpdf_Click" /></asp:LinkButton> 
     </ItemTemplate> 
    </asp:TemplateField> 
     </Columns> 
    </asp:GridView> 

我班

public class Thing 
{ 

    public string FilePath { get; set; } 
    public string FileName { get; set; } 
    public string FileDate { get; set; } 
} 

我pageLoad的

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/")); 
     List<Thing> lst = new List<Thing>(); 
     foreach (string filePath in filePaths) 
     { 
      lst.Add(new Thing() 
      { 

       //FileDate = File.GetCreationTime(filePath).ToShortDateString(), 
       FileDate = Path.GetFileName(filePath.Substring(0,35)), 
       FileName = Path.GetFileName(filePath.Substring(36)), 
       FilePath = filePath 
      }); 
     } 
     GridView1.DataSource = lst; 
     GridView1.DataBind(); 

我的下載按鈕

string filePath = (sender as LinkButton).CommandArgument; 
    Response.ContentType = ContentType; 
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath.Substring(36))); 
    Response.WriteFile(filePath); 
    Response.End(); 

我pdfview

string filePath = (sender as LinkButton).CommandArgument; 
    Response.ContentType = "Application/pdf"; 
    //Get the physical path to the file. 
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath.Substring(36))); 
    //Write the file directly to the HTTP content output stream. 
    Response.WriteFile(filePath); 
    Response.End(); 

我仍然無法查看瀏覽器的PDF格式...請幫助

回答

0

對於pdfview - 改變內容處置直插式的,而不是固定

Response.AppendHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(filePath.Substring(36))); 
+0

我得到服務器錯誤... startIndex不能大於字符串的長度。 – shaiToro 2014-11-14 21:04:37

+0

這看起來像您的filePath.Substring(36)問題 - 如果您的文件路徑小於36個字符。不知道爲什麼你說實話。 – Haedrian 2014-11-14 21:06:13

+0

它只是一個測試...只需要提取文件的名稱,因爲文件名前加上日期。我沒有刪除子串部分,但...訪問路徑'e \ dirname \'被拒絕。 – shaiToro 2014-11-14 21:12:02