1. 在struts.xml中的配置
<!-- 文件下载 -->
<action name="download" class="cn.ten.struts.DownAction">
<param name="inputPath">/upload</param>
<!-- 以流的方式返回 -->
<result name="success" type="stream">
<!-- 下载文件的类型 -->
<param name="contentType">application/octet-stream</param>
<!-- 下载源 -->
<param name="inputName">inputStream</param>
<!-- 处理文件 -->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!--缓冲流大小 -->
<param name="bufferSize">4096</param>
</result>
<interceptor-ref name="defaultStack"/>
</action>
2. 创建一个 DownAction, extendsActionSupport
public class DownAction extends ActionSupport{
//读取下载文件的目录
private String inputPath;
//下载文件的文件名
private String fileName;
//读取下载文件的输入流
private InputStream inputStream;
//下载文件的类型
private String contentType;
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
//创建inputStream输入流
public InputStream getInputStream() throws FileNotFoundException {
//获取文件路径
String path=ServletActionContext.getServletContext().getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"\\"+fileName));
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Override
public String execute() throws Exception {
return "success";
}
}
3.新建一个jsp页面
<body>
<a href="download.action?fileName=xy.jpg">点击此处下载文档</a>
</body>
4.启动你的tomcat运行