I want to give file download using java,struts2 and ajax.
On my html page there is a button called "export" clicking on which ajax call will be made which will execute a query and will create .xls file using code and I want to give that file for download to user without storing it on hard drive.
Does any one know how to do that using struts2 and ajax in java?
Is there any example available?
Let me know if you need more details from me...
Thanks.
amar4kintu
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());