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.

Line 2 sets the HTTP MIME type for the output stream. The default value is "text/html". As we want to store it as a file to the client system we specify it as “file”.
The AddHeader() method in Line 3 is used to add an HTTP header to the output stream. It accepts two parameters. First parameter is the name of the HTTP header to add value to and second is the value itself. In our case the parameter name is “content-disposition” and value is sent as "attachment" along with the file name. This is what that causes the opening of save file dialog. If we provide value of content-disposition as “inline” instead of save file dialog the file will be opened in the associated application.

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.

On clicking save, the save file dialog is opened where we can save the file to our system with the name that we have provided in the line 3 or we can provide a new name also.

1 comment:

Followers

Powered by Blogger.