[英]link to pdf file(asp.net)
我已经使用文件上传将pdf文件保存到数据库中。 现在我想从数据库中检索pdf文件,它必须链接到动态创建的链接按钮。 因此,对于每个链接按钮,我都有一个链接到它的pdf文件。 -如何使用C#在asp.net中执行此操作
我将编写一个通用处理程序,该处理程序将从给定的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>
...
首先,您必须从数据库中读取记录。
假设您具有以下表格结构:
ID,名称,BinaryPdfData
您可以使用ADO.NET,Linq2SQL或任何用于将“ ID”和“名称”“选择”到IEnumerable中的东西(例如List或DataSet)。
然后,将其绑定到ASP中继器,其中ItemTemplate包含一个LinkButton,并且Click事件背后的代码会将您重定向到某个下载页面,例如“ downloadpdf.aspx?id = {0}”。
其中{0}是记录的ID。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.