首先是action
package action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class FileDownloadAction implements Action {
private String filename;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public InputStream getTargetFile() throws FileNotFoundException {
File file = new File("E:\\jj.txt");
//指定下载文件名
setFilename(file.getName());
return new FileInputStream(file);
}
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
接着是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>
<package name="lee" extends="struts-default">
<action name="download" class="action.FileDownloadAction">
<result name="success" type="stream">
<!-- 指定下载文件类型 -->
<param name="contentType">text/plain</param>
<!-- 指定下载文件位置,必须和InputStream getTargetFile()中的get后的名字相同,首字母变小写 -->
<param name="inputName">targetFile</param>
<!-- 下载时显示的文件名 -->
<param name="contentDisposition">attachment;filename="${filename}"</param>
<!-- 指定下载文件的缓冲大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
然后,是jsp
<%@ 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 HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>文件下载的内容</h2>
第一个文件:<a href="lee/download.action">点击下载</a>
</body>
</html>