Wednesday, June 3, 2009

Downloading Binary content using ASP.NET and LINQ

Here’s the scenario. You have some binary data that is in a database. You want to use LINQ to SQL or LINQ to Entities to pull the data out of the database and return the user for viewing when they hit a particular url.

Let’s pretend you have a page called Download.aspx and you want to use the primary key in the url to specify what file should be downloaded when the user hits this page.

For example, if the url is http://myapp/Download.aspx?AttachmentID=123 where 123 is the primary key in a table called Attachment that has our binary data.

Below is an LINQ to Entities example, but a LINQ to SQL would be virtually identical.

protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["AttachmentID"]))
{
int attachmentID = Convert.ToInt32(Request.QueryString["AttachmentID"]);

using (MyEntities ctx = new MyEntities())
{
var attachment = ctx.Attachment.FirstOrDefault<MyAttachment>(a => a.ID == attachmentID);
if (attachment != null)
{

byte[] binaryData = attachment.DataField;
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachement; filename=\"{0}\"", attachment.FileName));
Response.ContentType = attachment.MimeType;
Response.BinaryWrite(binaryData);
Response.End();

}

}
}
}

No comments: