There are times when you would want to output a PDF or an office document to the user after clicking some link. Usually, if the file to be downloaded is readily available, a simple anchor tag will do, with the href attribute easily pointing to the existing file. But what if the file is to be generated “on the fly”?

In BEA’s Oracle’s WebLogic Platform 8.1, you cannot make use of the jsp:forward Javadoc annotation to forward the action method such a file — this annotation will only either allow you to proceed to an HTML (JSP) page, or yet another action method. What you can do though, is point it at some JSP that will do all the wonders for you.

The source code below (which is to be placed in the arbitrary JSP I mentioned) will require three prerequisites:

  1. filename — serves as the filename when the prompt to download appears;
  2. mimeType — the content type of the file (so it can be linked to the proper application); and,
  3. the File object — obviously, the file that needs to be downloaded also has to be available via the request object.

[sourcecode language=”java”]
<%
//String appendDate = new SimpleDateFormat("yyyy-MM-dd_HHmm").format(new Date());
String filename = request.getAttribute("filename").toString();
String mimeType = request.getAttribute("mimeType").toString();

String attachmentStr = "attachment; filename=" + filename;
response.setContentType(mimeType);
response.setHeader("Content-Disposition", attachmentStr);

File f = (File) request.getAttribute("theFile");
FileInputStream in = null;
int bytesRead = 0;
byte[] b = new byte[1024];

try{
in = new FileInputStream(f);

do{
bytesRead = in.read(b, 0, b.length);
response.getOutputStream().write(b, 0, bytesRead);
}while(bytesRead == b.length);

response.getOutputStream().flush();
}
finally{
if(in != null) in.close();
}
%>
[/sourcecode]

By the time this code completes, the JSP will not be shown as an ordinary webpage at all; the usual “Open / Save” dialog box will show up, asking the user to get the file from the server.

Many thanks to Martin’s post on StackOverflow for help on this one.