新建包com.action,在包中新建类DownloadAction,类代码如下:
package com.action;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public InputStream getDownloadFile() throws Exception{
InputStream in=(InputStream) ServletActionContext.getServletContext().getResourceAsStream(getPath());
return in;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
在src目录下新建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>
<package name="Struts2_AJAX_DEMO" namespace="/" extends="struts-default">
<action name="download" class="com.action.DownloadAction">
<param name="path">\download\a.jpg</param>
<result name="success" type="stream">
<!-- 下载文件类型定义 -->
<param name="contentType">image/jpg</param>
<!-- 下载文件处理方法 -->
<param name="contentDisposition">
attachment;filename="a.jpg"
</param>
<!-- 下载文件输出流定义 -->
<param name="inputName">downloadFile</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
在WebContent/WEB-INF下新建web.xml文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>internalDemo</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在WebContent目录下新建index.jsp文件,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!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>
<center>
<s:a action="download">download file</s:a>
</center>
</body>
</html>
将待下载文件放在WebContent目录下。