downloadaction.java
package com.h3.common.action; import java.io.file; import java.io.fileinputstream; import java.io.inputstream; import com.opensymphony.xwork2.actionsupport; public class downloadaction extends actionsupport{ private inputstream fileinputstream; public inputstream getfileinputstream() { return fileinputstream; } public string execute() throws exception { fileinputstream = new fileinputstream(new file("c:\\file-for-download.txt")); return success; } }
downloadpage.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <h1>struts 2 download file example</h1> <s:url id="filedownload" namespace="/" action="download" ></s:url> <div><div class="ads-in-post hide_if_width_less_800"> <script async class="lazy" data-original="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- 728x90 - after2ndh4 --> <ins class="adsbygoogle hide_if_width_less_800" data-ad-client="ca-pub-2836379775501347" data-ad-slot="3642936086" data-ad-region="h3region"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div></div><h2>download file - <s:a href="%{filedownload}">fileabc.txt</s:a> </h2> </body> </html>
定义下载文件的细节。 <param name=”inputname”> 值是从action的inputstream属性的名称。
struts.xml
<?xml version="1.0" encoding="utf-8" ?> <!doctype struts public "-//apache software foundation//dtd struts configuration 2.0//en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devmode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="show"> <result name="success">pages/downloadpage.jsp</result> </action> <action name="download" class="com.h3.common.action.downloadaction"> <result name="success" type="stream"> <param name="contenttype">application/octet-stream</param> <param name="inputname">fileinputstream</param> <param name="contentdisposition">attachment;filename="file-for-download.txt"</param> <param name="buffersize">1024</param> </result> </action> </package> </struts>
在浏览器中打开:http://localhost:8080/struts2download/