使用Java,Struts 2和AJAX的文件下载 [英] File download using Java, Struts 2 and AJAX

查看:119
本文介绍了使用Java,Struts 2和AJAX的文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用java,struts2和ajax给文件下载。

I want to give file download using java,struts2 and ajax.

在我的html页面上有一个名为export的按钮,点击哪个ajax调用这将执行一个查询,并将使用代码创建.xls文件,我想要将该文件下载到用户,而不将其存储在硬盘驱动器上。

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.

是否有任何一个知道如何在java中使用struts2和ajax?

Does any one know how to do that using struts2 and ajax in java?

有没有可用的例子?

让我知道你是否需要更多的细节...

Let me know if you need more details from me...

谢谢。

amar4kintu

amar4kintu

推荐答案

在这种情况下,您不必使用AJAX。只需让你的按钮提交表单到您的Struts操作,并采取行动使用流结果类型。

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.

示例:

在Struts XML中:

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>

您的操作将提供一个 public InputStream getInputStream()传递数据。

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

我假定您用于生成Excel文件的任何库( POI ?)可以将输出写入任意的 OutputStream

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

将这个转换为 InputStream 的一种快速而肮脏的方法:

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

这篇关于使用Java,Struts 2和AJAX的文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆