本系列博客汇总在这里:Struts2 汇总


源码工程文件为:struts2_16

Struts 文件下载对动作类 Action 的要求

在 Action 之中必须提供三个属性:

//提供一个输入流的属性,名字叫 inputStream 固定
private InputStream inputStream;
//定义文件的大小
private int filelength;
//定义文件名
private String fileName;
package com.wyx.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * action动作类充当模型对象
 */
public class DownAction extends ActionSupport
{

	// 提供一个输入流的属性,名字叫inputStream固定
	private InputStream inputStream;

	// 定义文件的大小
	private int filelength;

	// 定义文件名
	private String fileName;

	public InputStream getInputStream()
	{
		return inputStream;
	}

	public void setInputStream(InputStream inputStream)
	{
		this.inputStream = inputStream;
	}

	public int getFilelength()
	{
		return filelength;
	}

	public void setFilelength(int filelength)
	{
		this.filelength = filelength;
	}

	public String getFileName()
	{
		return fileName;
	}

	public void setFileName(String fileName)
	{
		this.fileName = fileName;
	}

	public String down() throws Exception
	{
		ServletContext sc = ServletActionContext.getServletContext();
		String realPath = sc.getRealPath("/upload/1.png");
		// 实例化输入流
		inputStream = new FileInputStream(realPath);
		// 给fileName赋值
		fileName = FilenameUtils.getName(realPath);
		// 对文件名做编码
		fileName = URLEncoder.encode(fileName, "UTF-8");
		// 给文件大小赋值
		filelength = inputStream.available();
		return super.SUCCESS;
	}

}

Action 的配置

<?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.devMode" value="true"></constant>
	
	<package name="down" extends="struts-default" namespace="/down">		
		<!-- 拦截器配置 -->
		<action name="weiyuxuan" class="com.wyx.action.DownAction" method="down">
			<result name="success" type="stream">
				<!-- 指定Action中输入流变量 -->
				<param name="inputName">inputStream</param>
				<!-- 设置响应的消息头 Content-Disposition -->
				<param name="contentDisposition">attachment;filename=${fileName}</param>
				<!-- 使用下载的方式来返回结果 -->
				<param name="contentType">application/octet-stream</param>
				<!-- 配置文件的大小 -->
				<param name="contentLength">${filelength}</param>
			</result>
		</action>		
	</package>
	
</struts>

Struts2(14)_Struts2 的文件下载_apache

如有错误,欢迎指正!