TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript Java Servlet Returning a File for Download in the Response

Java Servlet Returning a File for Download in the Response

User Rating: / 0
PoorBest 

You want to create a file and send it to the browser for the user to open and save. In the simplest example you pass a file to an OutputStream. Before we start we can assume that the object named data has been instantiated correctly and contains some sample XML data.

1.	response.setContentType("text/msword");
2.	response.setHeader("Content-Disposition", "attachment; filename=TomRed.doc");
3.	response.setHeader("Cache-Control", "no cache");

4.	OutputStream out = response.getOutputStream();

5.	out.write(data);

6.	out.flush();
7.	out.close();
  1. In line 1 we set the content type in this example we are returning a Microsoft Word document so we set it to text/msword. This can hold an number of types (an extensive list of MIME types can be found in HTML Extensions and MIME types). This is necessary as it tells the browser what type of file it will be dealing with.
  2. Line 2 is used to set the file name this is set as the Content-Disposition. In this example I also include the file is of type attachment, this attachment type alerts the browser that the file should be saved and not displayed inline(which is an alternative to attachment).
  3. In line 3 we set the cache attributes to no cache. I include this for a number of reasons, the first of which is to show you that this option is available, but also this is the solution to an Internet Explorer (IE6) bug which prevents file download. This skips the cache and so the file will be requested each time from the server and not from cache.
  4. Line 4 instantiates our OutputStream which we have called out. Notice we use getOutputStream() from the response.
  5. Line 5 uses the OutputStream method write to write out object called data to the response. This will cause a pop-up dialogue box similar to the images displayed to the left to be generated in your browser.
  6. In line 6 we flush the OutputStream to ensure our data has been written. This is due to the fact that just because the write method has been called does not mean the data has been written yet. Flush() ensure all that exists in the OutputStream has been written.
  7. Finally in line 7 we close the OutputStream. Once this is done it cannot be re-opened so ensure that there is nothing else left to write to the OutputStream, if there is then omit this line until after that has succeeded.