Contents
  1. 1. 功能介绍
  2. 2. Action代码
  3. 3. struts.xml配置

文章来源 www.kowen.cn

功能介绍

一个通用的struts2下载Action,下载链接传入两个参数:

  • fileName 文件服务器端路径 必须
  • downloadName参数 浏览器接收到的文件名,可省略后缀名,可不写

Action代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 下载
* @author kowen
*
*/
public class DownloadAction extends BaseAction{
//要下载的文件
private String fileName;
//下载后的名称
private String downloadName;
//返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流
public InputStream getDownloadFile() throws Exception
{
InputStream input = ServletActionContext.getServletContext().getResourceAsStream(fileName) ;
return input;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* 获取下载文件名
*/
public String getDownloadName() {
if(downloadName==null){
return fileName;
}
//如果下载文件名未指定后缀名,使用默认后缀名
if(downloadName.contains(".")){
return downloadName;
}else{
String suffix = fileName.substring(fileName.lastIndexOf("."));
return downloadName+suffix;
}
}
public void setDownloadName(String downloadName) {
this.downloadName = downloadName;
}
}

struts.xml配置

1
2
3
4
5
6
7
8
<action name="Download" class="DownloadAction类名或者spring中配置的beanid">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentDisposition">attachment;fileName="${downloadName}"</param>
<param name="inputName">downloadFile</param>
<param name="bufferSize">1024</param>
</result>
</action>
Contents
  1. 1. 功能介绍
  2. 2. Action代码
  3. 3. struts.xml配置