Struts2中文件下载

在struts.xml中配置如下

         <action name="download" class="cn.itcast.domain.User" method="download">
<result type="stream" name="success">
<param name="contentType">application/octet-stream</param>
<param name="inputStream">inputStream</param><!-- 输入是对应的动作类中的那个字段 -->
<param name="contentDisposition">attachment;filename=${filename}</param><!-- 要下载的文件名 -->
</result>

jsp页面中

user为action中传来的

           <c:url value="/user/download" var="url">
<c:param name="path" value="${user.path}"></c:param>
<c:param name="filename" value="${user.filename}"></c:param>
</c:url>
<a href="${url}">下载</a>

在User.java中

class User{
private String path; //文件保存的路径
private String filename; //文件名
//文件下载 固定名字
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
} public String download()
{
String storePath=ServletActionContext.getServletContext().getRealPath("/files");
System.out.println("before" +path +" "+ filename);
        //事实证明struts2中处理了相关参数, 并且通过url传输传给 path, filename中的值
// path=ServletActionContext.getRequest().getParameter("path");
// filename=ServletActionContext.getRequest().getParameter("filename");
System.out.println("after" +path +" "+ filename);
try {
inputStream=new FileInputStream(storePath+"\\"+path+"\\"+filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this.SUCCESS;
}
}
上一篇:Struts2 多文件下载


下一篇:struts2 实现文件下载方法汇总