struts2文件下载示例

首先先是不基于struts2的下载示例

在动作类action中的download(),代码如下:
public String download(){    
        try {
            FileInputStream fis = new FileInputStream(new File(path,newUser.getFilename()));//其中path为文件所在路径
            
            newUser.setInputStreamxxx(fis);
            
            /************************************************************************************************/
            
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="+newUser.getFilename());*/
            OutputStream os = response.getOutputStream();       
            byte[] b = new byte[1024];          
            int len;          
            while ((len=fis.read(b))!=-1) {
                os.write(b, 0, len);
            }
            os.flush();
            fis.close();
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return "download";
				}

基于struts2的的下载

* 动作类action中的download(),代码如下:
				public String download(){                                        
                                        //path为文件存放路径,newUser.getFilename为对应文件的文件名         
                                        FileInputStream fis = new FileInputStream(new File(path,newUser.getFilename()));
                                       //newUser为javabean的实例对象
                                        newUser.setInputStreamxxx(fis);
					return "download";
				}


	* 在javabean中,新增一个属性:inputStream类型的。用于下载获取文件流
			* 在struts.xml文件,配置如下:
				<!-- 用于下载 -->
				<result name="download" type="stream">
					<!-- 对应web中下载配置:application/x-msdownload -->
					<param name="contentType">application/x-msdownload</param>
                                        <!-- 对应javabean中inputStream类型的变量的名称-->
                                        <param name="inputName">inputStreamxxx</param>
                              <!-- 对应web中下载配置:response.setHeader("Content-Disposition", "attachment;filename="+newUser.getFilename()); -->
                                        <param name="contentDisposition">attachment;filename=${filename}</param>
                                        <!-- 对应web中下载配置:byte[] b = new byte[1024]; -->
                                        <param name="bufferSize">1024</param>
                               </result>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值