I have PDF file data in a SQL Server database, in the column type image
(bad previous db designer). What I need to do is read that binary data out to the client, so that they could download the PDF directly to their computer.
So far, my code is as follows:
SqlConnection con = new SqlConnection();
con.ConnectionString = "casIntranetConnectionString";
SqlCommand com = new SqlCommand("SELECT [File], [FileName] FROM [com].[catalog1] WHERE [FileName] = @filename");
com.Connection = con;
com.Parameters.AddWithValue("filename", Request.QueryString["filename"]);
con.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
Response.Clear();
Response.AddHeader("Content-Type", "application/pdf");
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["filename"] + ".pdf");
}
I'm assuming I'm going to need the reader to read out the bytes, but that's where I don't really know what I do. Any suggestions?
Thanks!
You can use the HttpResponse BinaryWrite method:
var bytes = reader.GetSqlBytes(index);
Response.BinaryWrite(bytes.Value);
As an aside, please consider separating responsibilities, you have a method which is responsible for accessing the database AND writing to the response. This will lead to maintenance problems in the future. See here for a useful blog post describing SOLID principles. Apologies if your code snippet was contrived, but in case any one else stumbles across this question figured I'd include a "but don't do it like this" disclaimer!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With