文件下载(struts2 Action)

客户端jsp请求Actin
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title>Struts2的文件下载</title>
		<meta name="website" content="http://www.crazyit.org" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	</head>

	<body>
		<h1>
			Struts2的文件下载
		</h1>
		<ul>
			<li>
				下载Struts2的Logo:
				<a href="download.action">下载图形文件</a>
			</li>
			<li>
				下载Struts2的Logo的压缩文件:
				<a href="download2.action">下载压缩文件</a>
			</li>
		</ul>
	</body>
</html>

Action处理
package com.lbx.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileDownloadAction extends ActionSupport{
	//依赖注入的属性,struts.xml中动态的指定
	private String inputPath;

	//只需要set方法
	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}
	
	/**
	 * 定义一个返回inputStream的方法,作为下载文件的入口
	 * 需要配置stream类型的结果时指定inputName参数
	 * inputName参数的值就是方法去掉get前缀,第一个字母小写的字符串
	 */
	public InputStream getTargetFile() throws Exception{
		return ServletActionContext.getServletContext()
		.getResourceAsStream(inputPath);
	}
	
}
 


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

	<constant name="struts.i18n.encoding" value="UTF-8"/>

	<package name="lee" extends="struts-default">

		<action name="download" class="com.lbx.action.FileDownloadAction">
			<!-- 指定被下载资源的位置 -->
			<param name="inputPath">\images\Java.gif</param>
			<!-- 配置结果类型为stream的结果 -->
			<result name="success" type="stream">
				<!-- 指定下载文件的文件类型 -->
				<param name="contentType">image/gif</param>
				<!-- 指定由getTargetFile()方法返回被下载文件的InputStream -->
				<param name="inputName">targetFile</param>
				<param name="contentDisposition">filename="crazyit.gif"</param>
				<!-- 指定下载文件的缓冲大小 -->
				<param name="bufferSize">4096</param>
			</result>
		</action>
	
		<action name="download2" class="com.lbx.action.FileDownloadAction">
			<!-- 定义被下载文件的物理资源 -->
			<param name="inputPath">\images\crazyit.zip</param>
			<result name="success" type="stream">
				<!-- 指定下载文件的文件类型 -->
				<param name="contentType">application/zip</param>
				<!-- 指定由getTargetFile()方法返回被下载文件的InputStream -->
				<param name="inputName">targetFile</param>
				<param name="contentDisposition">filename="crazyit.zip"</param>
				<!-- 指定下载文件的缓冲大小 -->
				<param name="bufferSize">4096</param>
			</result>
		</action>

    </package>
</struts>
 

 

你可能感兴趣的:(apache,html,jsp,xml,struts)