Download a file using Response headers

Hi All,

We sometime struggle implementing a functionality to download a file through browser download dialog window.

The below example will demonstrate the way we can download a file using response headers.

There are few steps you need to follow:

Step 1: First of all set the Content Type, for example if you want to set the file extension to Excel then.

response.setContentType(“application/vnd.ms-excel”);

Step 2: Now in this step we will set the response headers so that the browser can display the save and open prompt for the file.
Content-disposition is an extension to the MIME protocol that instructs a MIME user agent on how it should display an attached file.When Internet Explorer/Mozilla/any browser receives the header, it raises a File Download dialog box whose file name box is automatically populated with the file name that is specified in the header.

response.setHeader(“Content-Disposition”, “attachment;filename=” + MYFILE+”_TEST”+version_no+”.xls”)

Step 3: In this step we will add the data to the file which we are going to download.

response.getOutputStream().print(myData); // here my data is CSV formatted data

Step 4: Now access the servlet/jsp, the moment it loads you will see download window asking for save/open a file.

e.g http://localhost:8080/myapp/downlodReport

Hope this helps.


Thanks
R Vashis

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s