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.
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.
Hope this helps.