struts2文件下载功能实现代码如下所示:
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
|
public class DownLoadAction extends ActionSupport { /** * */ private static final long serialVersionUID = 5879762231742395104L; private String fileName; //用户请求的文件名 private String inputPath; //下载资源的路径(在struts配置文件中设置) public void setInputPath(String inputPath) { this .inputPath = inputPath; } public String getInputPath() { return inputPath; } public void setFileName(String fileName) { this .fileName = fileName; } public String getFileName() { return fileName; } public String downloadFile() throws Exception { ServletContext context = ServletActionContext.getServletContext(); String downloadDir = context.getRealPath( "/upload" ); String downloadFile = context.getRealPath(inputPath); //防止用户请求不安全的资源 if (!downloadFile.startsWith(downloadDir)) { return null ; } return "download_success" ; } /* * 获取输入流资源 */ public InputStream getInputStream() throws Exception { String path = inputPath + File.separatorChar + new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); return ServletActionContext.getServletContext().getResourceAsStream(path); } /* * 获取下载时文件默认的文件名 */ public String getDownloadFileName() { String downloadFileName = fileName; try { downloadFileName = URLEncoder.encode(downloadFileName, "ISO-8859-1" ); } catch (UnsupportedEncodingException e) { e.getMessage(); e.printStackTrace(); } return downloadFileName; } } |
jsp文件:
1
2
3
4
5
6
|
<li> <a href= "<%=path%>/download_DownLoadAction_downloadFile.action?fileName=dwr.jar" >dwr.jar文件下在</a> </li> <li> <a href= "<%=path%>/download_DownLoadAction_downloadFile.action?fileName=Struts2教程.pdf" >Struts2教程.pdf文件下在</a> </li> |
struts.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<action name= "download_*_*" class = "com.wang.action.{1}" method= "{2}" > <param name= "inputPath" >/upload</param> <!-- result type设置为stream --> <result name= "download_success" type= "stream" > <!-- MIME类型 --> <param name= "contentType" >application/octet-stream</param> <!-- inputName的值与action获取输入流资源的方法名相对应(action中定义getInputStream方法,并且返回类型为InputStream) --> <param name= "inputName" >inputStream</param> <!-- 设置带附件的文件 动态获取文件名(action中定义getDownloadFileName方法) --> <param name= "contentDisposition" >attachment;filename= "${downloadFileName}" </param> <!-- 设置缓冲大小 --> <param name= "bufferSize" > 2048 </param> </result> </action> |
以上所述是小编给大家介绍的Struts2实现文件下载功能代码分享(文件名中文转码)的相关内容,希望对大家有所帮助!