DownloadAction.java
package com.tw511.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 src="//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="yiibairegion"></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.tw511.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/