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

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...