位置:首頁 > Java技術 > Struts2教學 > Struts2下載文件實例

Struts2下載文件實例

這是一個Struts2的例子來說明使用定製返回類型,允許用戶下載文件。web工程的文件夾結構如下所示:

1. Action

在Action類中,聲明一個 InputStream 的數據類型和getter方法。

DownloadAction.java

package com.gitbook.netmon.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" 
     style="display:inline-block;width:728px;height:90px"
     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.gitbook.netmon.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. http://www.gitbook.net/struts/struts-download-file-from-website-example.html
  4. http://www.gitbook.net/java/how-to-download-file-from-website-java-jsp.html
  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