Struts文件下载(静态)

前言:在实际的开发中,我们可能需要动态下载和静态下载,

动态下载:例如我上传了一个文件,你想下载,那就必须动态生成下载链接,因为我服务器一开始是不知道我上传的东西是什么,放在那里,

静态下载:比如一些网站一些固定的资源,提供给我们下载

这里我写的是关于静态的下载实现流程:
第一步:

编写Action类,响应下载的的超链接:
  1)声明contentType(文件类型)contentLength( 下载的文件的长度)contentDisposition(响应信息的类型)这三个属性,并提供这三个属性的set和get方法

  ps:其中contentDisposition属性一定要声明而且也要指定属性值,:因为默认的属性值,无法响应下载的result的type类型的Stream

  具体声明如下:

 1     private String contentType;
 2     private long contentLength;
 3     private String contentDisposition;
 4     private InputStream inputStream;
 5     
 6     public String getContentType() {
 7         return contentType;
 8     }
 9 
10     public long getContentLength() {
11         return contentLength;
12     }
13 
14     public String getContentDisposition() {
15         return contentDisposition;
16     }
17     
18     public InputStream getInputStream() {
19         return inputStream;
20     }
21     

2提供inputstream:(提供一个输入流给浏览器下载)
代码如下:

 1     private InputStream inputStream;
 2         public InputStream getInputStream() {
 3         return inputStream;
 4     }
 5 
 6     
 7     public String execute() throws Exception {
 8 
 9         //确定各个成员变量的值
10         
11         contentDisposition = "attachment;filename=hidden.html";
12         
13         ServletContext servletContext = ServletActionContext.getServletContext();//取得ServletContext对象
15         String fileName = servletContext.getRealPath("/File/hidden.html");//取得需要下载文件的路径
16         inputStream = new FileInputStream(fileName);
17         
18         
19         return SUCCESS;
20     }
原文地址:https://www.cnblogs.com/jeremy-blog/p/3995451.html