1 package com.test.action;
2
3 import java.io.InputStream;
4 import java.io.UnsupportedEncodingException;
5 import javax.servlet.http.HttpServletResponse;
6 import org.apache.struts2.ServletActionContext;
7 import com.opensymphony.xwork2.ActionSupport;
8
9
10 /**
11 * Action that file download
12 * @author Luxh
13 */
14 public class FileDownloadAction extends ActionSupport{
15
16 private static final long serialVersionUID = 401395607049416796L;
17
18 /**
19 * 文件名
20 * 接收请求传递的文件名
21 */
22 private String fileName;
23
24 public String getFileName() {
25 return fileName;
26 }
27
28 public void setFileName(String fileName) throws UnsupportedEncodingException {
29 //用UTF-8重新编码文件名,解决中文乱码
30 this.fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
31 }
32
33
34 /**
35 * 下载的文件入口
36 * @throws UnsupportedEncodingException
37 */
38 public InputStream getInputStream() throws UnsupportedEncodingException{
39 HttpServletResponse response = ServletActionContext.getResponse();
40 response.setHeader("Content-Disposition", "attachment;fileName="
41 + java.net.URLEncoder.encode(fileName,"UTF-8"));
42 //java.net.URLEncoder.encode(fileName,"UTF-8") 编码转换,解决乱码
43 return ServletActionContext.getServletContext().getResourceAsStream(fileName);
44 }
45
46
47
48 @Override
49 public String execute() throws Exception {
50 return SUCCESS;
51 }
52
53
54
55 }
struts.xml配置文件:
1 <action name="fileDownload" class="com.test.action.FileDownloadAction"> 2 <result name="success" type="stream"> 3 <!-- 下载文件类型定义 --> 4 <param name="contentType">application/octet-streamparam> 5 <!-- 下载文件流定义 --> 6 <param name="inputName">inputStreamparam> 7 <!-- 下载文件的缓冲大小 --> 8 <param name="bufferSize">4096param> 9 result> 10 action>
jsp页面:
1 <a href="fileDownload.action?fileName=">文件下载a>
fileName的值在生成页面的时候动态生成。
需要注意的是fileName是文件在项目中的完整路径,否则会报inputStream流找不到的异常。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26481450/viewspace-731193/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26481450/viewspace-731193/