下载Action编写
/**
*
*/
package com.test.action;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
/**
* @author Administrator
*
*/
public class DownLoadAction {
// 获取下载文件的名称
private String value;
/**
* @return the value
* @throws Exception
*/
public String getValue() throws Exception {
return value;
}
/**
* @param value the value to set
* @throws Exception
*/
public void setValue(String value) throws Exception {
this.value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
}
/**
* 将下载的文件读取到内存流中
* @return
* @throws Exception
*/
public InputStream getDownLoadFiles() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(value,"utf-8"));
return ServletActionContext.getServletContext().getResourceAsStream("/files/"+value);
}
/**
* 提供下载文件的方法
* @return
*/
public String downLoad() {
return "success";
}
}
=======================================================================
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.action.extension" value="do"/>
<constant name="struts.multipart.maxSize" value="1000000"/>
<package name="test" extends="struts-default">
<action name="upload" class="com.test.action.UploadAction" method="upload">
<result>/index.jsp</result>
</action>
<action name="downloadPage">
<result>/down.jsp</result>
</action>
<action name="download" class="com.test.action.DownLoadAction" method="downLoad">
<result type="stream">
<!--<param name="contentDisposition">attachment;fileName=${value}</param>
--><param name="inputName">downLoadFiles</param>
<param name="contentType">text/plain</param>
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
down.jsp页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="org.apache.struts2.ServletActionContext"%>
<%@page import="java.io.File"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="base" %>
<%
String realPath = ServletActionContext.getServletContext().getRealPath("/files");
File file = new File(realPath);
File[] files = file.listFiles();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base:bean />
<title>My JSP 'download.jsp' starting page</title>
</head>
<body>
<h3>文件下载列表</h3>
<% for(int i=0;i<files.length;i++) {
String fname = java.net.URLEncoder.encode(files[i].getName(), "UTF-8");
%>
<ul>
<li><%=files[i].getName() %><a href="download.do?value=<%=fname %>">下载</a></li>
</ul>
<%} %>
</body>
</html>