Struts2下載檔案範例


這是一個Struts2的例子來說明使用客製化返回型別,允許使用者下載檔案。web工程的檔案夾結構如下所示:

1. Action

在Action類中,宣告一個 InputStream 的資料型別和getter方法。

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;
	}
}

2. 檢視檔案

一個正常的頁面,有一個下載連結,用於下載檔案。

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>

3. struts.xml

定義下載檔案的細節。 <param name=」inputName」> 值是從Action的InputStream屬性的名稱。

閱讀Struts2的資料流結果文件以了解更詳細資訊。

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>

4. 執行結果

在瀏覽器中開啟:http://localhost:8080/struts2download/

參考

  1. http://struts.apache.org/2.x/docs/stream-result.html
  2. http://www.iana.org/assignments/media-types/
  3. /
  4. /
  5. http://struts.apache.org/2.x/docs/how-can-we-return-a-text-string-as-the-response.html
程式碼下載(struts2download) - http://pan.baidu.com/s/1jGg0Lzo