Struts实现文件下载
1.操作下载的Action
package com.zb.action;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport {
private String filename;//要下载的文件名
//这个方法必须有
public InputStream getInputStream() throws Exception {
//获取上传文件夹的路径
String path=ServletActionContext.getServletContext().getRealPath("upload/");
return new FileInputStream(path+"/"+filename);
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
2.Struts配置文件
<?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="default" namespace="/file" extends="struts-default">
<!-- 这两个是上传时候的两个Action 单文件上传和多文件上传 -->
<action name="uploadAction" class="com.zb.action.UploadAction" method="up">
<result name="success">/ok.jsp</result>
</action>
<action name="manyUploadAction" class="com.zb.action.ManyUploadAction" method="up">
<result name="success">/manyOk.jsp</result>
</action>
<!-- 下载 -->
<action name="download" class="com.zb.action.DownloadAction">
<result type="stream">
<!-- 指定文件下载的执行方法 -->
<!-- 参数值为Action中的getInputStream()方法的去掉get,并且首字母小写,因为后台会自动加get去找该方法-->
<param name="inputName">inputStream</param>
<!--- 这里的filename的值为Action中的成员变量 -->
<param name="contentDisposition">
attachment;filename="${filename}"
</param>
</result>
</action>
</package>
</struts>
至此,已经完成了,下面就是我们的页面来执行这个下载的方法了
3.JSP页面下载链接
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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 'ok.jsp' starting page</title>
</head>
<body>
<!-- <s:property value="uploadFileName"> 这个值为上传文件的文件名 -->
<a href="file/download?filename=<s:property value="uploadFileName"></s:property>">down</a>
</body>
</html>
如有不足请指正。