struts2文件下载

struts2 文件下载类是很简单的,代码:

 1  package  test.filedown
 2 
 3  import  java.io.InputStream;
 4  import  com.forlink.wps.template.dao.TemplateJackrabbitDao;
 5  import  com.forlink.wps.template.dao.impl.TemplateJackrabbitDaoImpl;
 6  import  com.forlink.wps.template.dto.TemplateDTO;
 7  import  com.opensymphony.xwork2.ActionSupport;
 8 
 9  public   class  FileDownloadAction  extends  ActionSupport
10  {
11 
12       private  String    inputPath;
13 
14       private  String    contentType;
15      
16       private  String filename;
17      
18 
19       public  InputStream getInputStream()  throws  Exception
20      {
21         try {
   HttpServletResponse response=ServletActionContext.getResponse();
   String downloadfile=java.net.URLEncoder.encode(filename,"UTF-8");
   response.setContentType("application/x-msdownload");
   response.setHeader("Content-Disposition", "attachment;filename=/"" + new String(downloadfile.getBytes("UTF-8"),"GBK") + "/"");
   System.out.println("文件路径:"+inputPath);
   
   return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
22 
23      }
24 
25       public  String execute()  throws  Exception
26      {
27          inputPath = " /image/close_w.gif " ; // 要下载的文件名称
28          filename = " test.gif " // 保存文件时的名称
29          contentType = " image/gif " ; // 保存文件的
30               return  SUCCESS;
31      }
32 
33 
34       public  String getContentType()
35      {
36           return  contentType;
37      }
38 
39       public   void  setContentType(String contentType)
40      {
41           this .contentType  =  contentType;
42      }
43 
44       public  String getFilename()
45      {
46           return  filename;
47      }
48 
49       public   void  setFilename(String filename)
50      {
51           this .filename  =  filename;
52      }
53  }
54 

主要是在Action的配置上,配置文件如下:

< action  name ="filedownload"
            class
="test.filedown.FileDownloadAction" >
            
< result  name ="success"  type ="stream" >
                
< param  name ="contentType" > ${contentType} </ param >
                
< param  name ="inputName" > inputStream </ param >                 
                
< param  name ="bufferSize" > 4096 </ param >
                
< param  name ="contentDisposition" > filename="${filename}" </ param >
                
< param  name ="" ></ param >
            
</ result >
</ action >

    contentType:指定被下载文件的文件类型。
 inputName:指定被下载文件的入口输入流。
 contentDisposition:指定下载的文件名。
 bufferSize:指定下载文件时的缓冲大小。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值