2009-11-27 99 views
0

我已经使用文件上传将pdf文件保存到数据库。现在我想从数据库中检索pdf文件,并且它必须链接到动态创建的链接按钮。所以对于每个链接按钮我有一个pdf文件链接到它。 - 如何使用C#在asp.net中做到这一点#链接到PDF文件(asp.net)

+4

恐怕你需要更加具体地了解PDF文件如何存储在数据库中,然后才能在这里得到明智的答案。我们在这里是陌生人,所以我们不知道你的应用程序是如何工作的。 – 2009-11-27 07:50:08

+1

你使用什么数据库(SQL Server?)? PDF文件如何存储在数据库中?链接按钮是如何创建的? – 2009-11-27 07:54:46

回答

1

首先,你必须从数据库中读取记录。

比方说,你有如下表结构:

ID,姓名,BinaryPdfData

您使用ADO.NET,LINQ2SQL或者您使用的是“选择” Id和名称 到一个IEnumerable什么(例如一个List或DataSet)。

然后你绑定的是一个ASP中继器,其中ItemTemplate中 包含一个LinkBut​​ton和后面的代码为Click事件将 然后您重定向到例如“downloadpdf.aspx?ID = {0}”

一些下载页面

其中{0}是记录的标识。

download.aspx页面从数据库 中读取指定记录,并将二进制pdf数据放入缓冲区数组中。

接下来你就必须设置内容类型等等

我没有时间来建立一个很好的例子,但你可能会需要这样的:

Response.Clear() 

//set the content type to PDF 
Response.ContentType = "application/pdf" 

//add content type header 
Response.AddHeader("Content-Type", "application/pdf") 

//set the content disposition 
Response.AddHeader("Content-Disposition", "inline;filename=helloworld.pdf") 

//write the buffer with pdf file to the output 
Response.BinaryWrite(Buffer) 

Response.End() 
2

我会写一个通用处理器将从给定的ID从数据库读取的PDF:

public class PdfHandler : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     int id; 
     if (int.TryParse(context.Request["id"], out id)) 
     { 
      id = 0; 
     } 

     var connectionString = ConfigurationManager.ConnectionStrings["some_db"].ConnectionString; 
     using (var connection = new SqlConnection(connectionString)) 
     using (var command = connection.CreateCommand()) 
     { 
      connection.Open(); 
      command.CommandText = "select image from some_table where image_id = :id"; 
      command.Parameters.AddWithValue("id", id); 
      using (var reader = command.ExecuteReader()) 
      { 
       if (reader.Read()) 
       { 
        context.Response.ContentType = "application/pdf"; 
        var cd = new ContentDisposition(); 
        cd.FileName = "test.pdf"; 
        cd.Inline = true; 
        context.Response.AddHeader("Content-Disposition", cd.ToString()); 

        long bytesRead; 
        int size = 1024; 
        var buffer = new byte[size]; 
        long dataIndex = 0; 
        while ((bytesRead = reader.GetBytes(0, dataIndex, buffer, 0, buffer.Length)) > 0) 
        { 
         var actual = new byte[bytesRead]; 
         Buffer.BlockCopy(buffer, 0, actual, 0, (int)bytesRead); 
         context.Response.OutputStream.Write(actual, 0, actual.Length); 
         dataIndex += bytesRead; 
        } 
       } 
       else 
       { 
        context.Response.ContentType = "text/plain"; 
        context.Response.Write("Not found"); 
        context.Response.StatusCode = 404; 
       } 
      } 
     } 
    } 

    public bool IsReusable 
    { 
     get { return false; } 
    } 
} 

而在aspx页面只是把引用该处理器主播:

<a href="/PdfHandler.ashx?id=1">pdf 1</a> 
<a href="/PdfHandler.ashx?id=2">pdf 2</a> 
<a href="/PdfHandler.ashx?id=3">pdf 3</a> 
...