Downloading files with ASP.NET using Save As Dialog
This article explains how to download a file that is stored in the database with the possibility of forcing the browser to open a “Save As” dialog box to save the file on to the client system.
The content of the file is stored in a column of a table of image data type.
Such a dialog-box for saving a file can be displayed by using HttpContext.Current.Response property.
HttpContext is a class that encapsulates all HTTP-specific information about an individual HTTP request. The property HttpContext.Current gets the HttpContext object for the current HTTP request.
Here is an example:
1. HttpContext.Current.Response.Clear(); 2. HttpContext.Current.Response.ContentType = "file"; 3. HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName); 4. // Remove the charset from the Content-Type header. 5. HttpContext.Current.Response.Charset = ""; 6. byte [] buffer = (byte[])(dsFile.Tables[0].Rows[0]["FILE_CONTENT"]); 7. HttpContext.Current.Response.BinaryWrite(buffer); 8. // End the response. 9. HttpContext.Current.Response.End(); |
Line 1 clears all content output from the buffer stream.
In the Line 7 we are actually writing the contents of the file, as binary characters, to the HTTP output stream. Method BinaryWrite() is used for this purpose. This method takes a parameter buffer which is a byte array containing bytes to be written to the HTTP output stream. In our case the content of this buffer are fetched from the database into a dataset dsFile with column “FILE_CONTENT” corresponding to the bytes to be written.
The End() method in Line 9, sends all currently buffered output to the client, stops execution of the page, and raises the Application_EndRequest event. This is when we see a message asking us to save or open the file, displaying the information about the file, like file type, file name.