标签:
首先搭建好struts2的开发环境,先新建一个下载的页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'download.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">
</head>
<body>
<a href="${pageContext.request.contextPath }/download.action">下载</a>
</body>
</html>
在WebRoot下面建立一个download文件夹。里面放一个1.txt文件
之后再新建一个DownloadAction类,然后查看struts2的文档得知进行文件下载要设置一下参数,一般前四个要动态的生成
text/plain).
inline, values are typically attachment;filename="document.pdf".
inputStream).
1024).
true)
package cn.lfd.web.download;
import java.io.FileInputStream;
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 contentType;//要下载的文件的类型
private long contentLength;//要下载的文件的长度
private String contentDisposition;//Content-Disposition响应头,一般为attachment;filename=1.txt
private InputStream inputStream;//文件输入流,默认是InputStream
public String getContentType() {
return contentType;
}
public long getContentLength() {
return contentLength;
}
public String getContentDisposition() {
return contentDisposition;
}
public InputStream getInputStream() {
return inputStream;
}
@Override
public String execute() throws Exception {
contentType = "text/txt";
contentDisposition = "attachment;filename=1.txt";
//得到要下载的文件的路径
String dir = ServletActionContext.getServletContext().getRealPath("/download/1.txt");
inputStream = new FileInputStream(dir);
contentLength = inputStream.available();
return super.execute();
}
}
最后在struts.xml配置文件中配置一下,注意一定要把result的type设置成stream
<action name="download" class="cn.lfd.web.download.DownloadAction"> <result type="stream"> <param name="bufferSize">2048</param> </result> </action>这样用struts2就可以实现文件的下载
标签:
原文地址:http://blog.csdn.net/qq_22498277/article/details/51345719