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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="download.action?filepath="filePath>下载</a>
</body>
</html>
struts2配置文件struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="2097152"></constant>
<package name="demo" extends="struts-default">
<action name="download" class="org.lzh.action.DownloadAction" method="dodownload">
<result name="success" type="stream"><!--type 为 stream 应用 StreamResult 处理-->
<param name="contentType">image/pjpeg</param><!--默认为 text/plain-->
<!-- 默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法 -->
<param name="inputName">inputStream</param>
<!-- 默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名 -->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param><!-- 输出时缓冲区的大小 -->
</result>
</action>
</package>
</struts>
下载action
package org.lzh.action;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport {
private static final long serialVersionUID = 4926728383691954633L;
private InputStream inputStream;
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String dodownload()throws Exception{
inputStream=ServletActionContext.getServletContext().getResourceAsStream("images/123.jpg");
fileName = "123.gif";
return Action.SUCCESS;
}
}