File download using Java, Struts 2 and AJAX File download using Java, Struts 2 and AJAX ajax ajax

File download using Java, Struts 2 and AJAX


You don't have to use AJAX in this case. Just have your button submit the form to your Struts action, and have the action use the stream result type.

Example:

In your Struts XML:

<result name="download" type="stream">    <param name="contentDisposition">attachment;filename=report.xls</param>    <param name="contentType">application/vnd.ms-excel</param>    <param name="inputName">inputStream</param>    <param name="bufferSize">1024</param></result>

Your action will then provide a public InputStream getInputStream() to pass along the data.

I presume that whatever library you're using to generate the Excel files (POI?) can write the output to an arbitrary OutputStream.

A quick-and-dirty way to convert that to an InputStream:

// Using Workbook from Apache POI for example...Workbook wb;// ...ByteArrayOutputStream bos = new ByteArrayOutputStream();wb.write(bos);InputStream bis = new ByteArrayInputStream(bos.toByteArray());


Just for your reference, we can do the same using Annotation:

public class MyAction {    private InputStream fileInputStream;    private String logoName;    @Action(value="/downloadLogo",         results={            @Result(name="success", type="stream",             params = {                    "contentType", "application/image/gif",                    "inputName", "fileInputStream",                    "contentDisposition", "filename=\"${logoName}\"",                    "bufferSize", "1024"            })        }               )        public String downloadLogo() throws Exception {        logoName = "test.jpg";            fileInputStream = new FileInputStream(new File("DirePath", logoName));    }}


As a follow-up to amar4kintu's question regarding files saved as ExportReport.action instead of report.xls, this happens in IE if the following format is not followed in your struts.xml file:

<result name="download" type="stream">        <param name="contentDisposition">attachment;filename="${flashcardSetBean.title}.xlsx"</param>        <param name="contentType">application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</param>        <param name="inputName">inputStream</param>        <param name="bufferSize">1024</param></result>

It seems like the contentDisposition line in particular must indicate that the file is an attachment and that the filename is surrounded by quotes.