本文实例为大家分享了struts2下实现文件下载功能,供大家参考,具体内容如下
下面以实现一个图片下载功能为例:
1. 项目结构
2. web.xml
struts 2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts 2 /* index.jsp 30
3.DownloadAction.java
package com.action;
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 path;
//path属性的getter方法
public String getPath(){
return path;
}
//path属性的setter方法
public void setPath(String path){
this.path = path;
}
//返回inputstream,文件下载关键方法
public java.io.InputStream getDownloadFile() throws Exception{
InputStream in = ServletActionContext.getServletContext().getResourceAsStream(getPath());
return in;
}
public String execute() throws Exception{
return SUCCESS;
}
}
4.struts.xml
image/jpeg attachment;filename="a.jpg" downloadFile 1024
5.index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>首页 欢迎来到首页,点下面链接去下载一个文件
">下载
6.文件路径
项目中要提前建立好download目录,和里面要存在有a.jpg文件,否则,下载会失败。
7.功能入口
项目发布到服务器后,用浏览器访问项目中的index.jsp ,点击下载链接,就可以弹出“下载”对话框。



