1. 程式人生 > >struts2檔案下載例項

struts2檔案下載例項

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<a href="upload/20161012_094556771_7237.doc">20161012_094556771_7237.doc</a><br/>
	<a href="down?file=20161012_093223812_7769.jpg">20161012_093223812_7769.jpg</a>
	
</body>
</html>

action

package com.zucc.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport implements ServletContextAware{
	
	private String file;
	
	private InputStream is;
	
	private ServletContext application;
	
	private String downDir;
	
	public String getFile() throws UnsupportedEncodingException {
		//解決傳送到網頁檔名出現亂碼的問題
		return new String(this.file.getBytes("utf-8"),"ISO-8859-1");
	}

	public void setFile(String file) throws Exception {
		//解決從網頁獲取檔名的亂碼問題  
       this.file = new String(file.getBytes("ISO-8859-1"),"utf-8");
	}
	
	public InputStream getIs() {
		return is;
	}

	public void setIs(InputStream is) {
		this.is = is;
	}


	@Override
	public String execute() throws Exception {
		System.out.println("FileDownloadAction execute...");
		System.out.println("file:"+file);
        //獲取檔案路徑
		this.is = new FileInputStream(this.downDir + "/" + file);
		return SUCCESS;
	}

	@Override
	public void setServletContext(ServletContext context) {
		this.application = context;
		this.downDir = application.getRealPath("/upload");
	}
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
   <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
    
 	<package name="default" namespace="/" extends="struts-default">
 	
 	<action name="down" class="com.zucc.action.FileDownloadAction">
 		<result name="success" type="stream">
 		<!-- 這個is名字要和FileDownloadAction.java類中的型別為InputStream的變數名一致 -->
 			<param name="inputName">is</param>
 			
 		<!-- 1)  contentDisposition預設是 inline(內聯的), 比如說下載的檔案是文字型別的,就直接在網頁上開啟

,不能直接開啟的才會開啟下載框自己選擇
			 2)  attachment :下載時會開啟下載框
			 3)  fileName="${fileName}" :在這定義的名字是一個動態的,該名字是顯示在下載框上的檔名字
 		 -->
 			<param name="contentDisposition">attachment;fileName="${file}"</param>

		<!-- 一次性讀取的位元組大小 -->
 			<param name="bufferSize">1024</param>
 		</result>
 	</action>
    </package>
</struts>
注意:結果型別必須要寫成 type="stream"  ,與之對應的處理類是 org.apache.struts2.dispatcher.StreamResult