Sometimes I had to display a dinamically generated file to the browser without save it locally on the server where I produce it.
HTTP allows you all of this, but browsers implemented the feature in different ways, so here I will report a method for sending a stream of binary data to a browser that works for every browser, in particular IE6.
The environment I use for this example is:
- a Java Dynamic Web project
- a Java servlet container (e.g Apache Tomcat)
- Apache Struts 2 library to apply MVC on my web project
The struts.xml fragment for the action that rertieves the bytes and send them to the browser is as follows:
<action name="getFile" class="my.app.ExportFileAction" method="getFile"> <result type="stream" name="success"> <param name="contentType">${mimeType}</param> <param name="inputName">exportStream</param> <param name="contentDisposition">attachment; filename=${fileName}</param> </result> </action>
The getFile() method of the my.app.ExportFileAction class is as follows:
public String getFile() { try { exportStream = new ByteArrayInputStream(getFileContent()); mimeType = "application/pdf"; // in this example I use PDF mime fileName = "ExportedFile.pdf"; // the name we want to be proposed in the Save as... dialog } catch (Exception e) { return ERROR; } return SUCCESS; }
exportStream, mimeType and fileName are members of my JavaBean Action class, each of which must have its getter and setter:
protected String mimeType; protected String fileName; protected InputStream exportStream;
getFileContent() will be the method that retrieves the bytes of your file to send to the browser; here I will report only the method signature:
private byte[] getFileContent() {}
Great! Your code works very well. Thank you very much.
P.S.: Insomma…grazie!
Happy to have been useful; you’re welcome…
Insomma… di nulla!