File download using Java, Struts 2 and AJAX

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

Answers


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());

Need Your Help

Correct way to set the socket send buffer size on linux?

java performance sockets networking

I have an NIO server that gets small client requests that result in ~1meg responses. The server uses the following to accept a new client:

javascript find an object with specific properties in an array

javascript arrays object

I need to make an extension to existing code, can't change it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.