How to create download-dialog for file in database

If you store your files in a database (as blob) you do not have a physical path to the file.
How can you let the user download the file when the file isn’t fysically there?

Here is the code you need to create such a download dialog.

In my case the documents (in the database) have a guid. With this guid I can get the unique file.

The code needs to be triggered so you can use a for example a button with an OnClick event.
When you click the button following code will be executed:

You can also redirect to a new page with the documentGuid as parameter. Then the code will be executed in the Page_Load event:

protected void Page_Load(object sender, EventArgs e)
    Attachment attachment = documentManager.GetAttachment(new Guid(Request["documentGuid"]));
    if (attachment != null)
        Response.ContentType = “application/octet-stream”;
        Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, attachment.Document.Name));

Explanation: Method for getting data from the database is LINQ. I use the ADO.NET Entity framework. For that reason you see the Attachment object. This is simply the tablename in my SQL DB. So the attachment.FileData simply returns the binary of the file.

Here an example of what is in the database:

!!! Remark:
When your button is in an updatepanel the code fill fail. You will get following error on ScriptResource.axd:
This problem can be solved by using the scenario where you redirect to a new page and handle the page-load event to display the file.

Leave a Reply

Your email address will not be published. Required fields are marked *