struts2实现文件下载

来源:互联网 发布:数据分析师适合女生嘛 编辑:程序博客网 时间:2024/04/29 13:55

struts.xml文件:

        <action name="exportToExcel" class="com.asiainfo.business.SheetManageAction" >    <result name="success" type="stream"><!-- 指定下载文件的内容类型,text/plain是默认类型 -->  <param name="contentType">text/plain</param>        <!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性名是inputStream,那么可以省略这个参数 -->  <param name="inputName">inputStream</param>  <param name="contentDisposition">attachment;filename="${filename}"</param>  <param name="bufferSize">2048</param>           </result>       </action>
参数解释:
contentType 内容类型,和互联网MIME标准中的规定类型一致,例如text/plain代表纯文本,text/xml表示XML,image/gif代表GIF图片,image/jpeg代表JPG图片; inputName 下载文件的来源流,对应着action类中某个类型为Inputstream的属性名,例如取值为inputStream的属性需要编写getInputStream()方法; contentDisposition 文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件。取值为: attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt。如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline; filename="struts2.txt" ;bufferSize 下载缓冲区的大小;

后台Action:

public String exportToExcel(){return SUCCESS;}InputStream inputStream;public InputStream getInputStream() throws Exception {//具体读取文件的方法    }

前台JSP:

window.open("${pageContext.request.contextPath}/命名空间名/exportToExcel.action?参数名="+变量存的参数值, "_self");
参数解释:

_self 表示当前窗口_blank 表示新窗口_parent 表示父窗口_top 表示顶层窗口
延伸:
javascript中 open的参数定义为:open( [sURL] [, sName] [, sFeatures] [, bReplace])其中第二个参数定义打开的窗口名,或者用_blank指定新窗口,_top指定顶级窗口等。这个名字以后能用在A或者form的target参数中。而窗口的长宽等是定义在sFeatures中,如height=200,width=400最后一个参数是true/false,用来指定是否在替换当前浏览器历史中的地址


0 0
原创粉丝点击