HOWTO: stream response with struts 2 that works in IE6

Web browser
Image via Wikipedia

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:

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() {}

2 pensieri su “HOWTO: stream response with struts 2 that works in IE6

Lascia un commento