Ext+Struts2.0实现文件下载

才开始用Ext,上手还算简单,但不得不感叹Ext对Js炉火纯青的封装。

现把纠结了我半天的Ext+Struts2.0实现文件下载分享给大家。中间的大部分代码都是从网上查到了资料,然后进行了整理,因为网上的资料实在有点乱,而且没有一份答案能单独解决我的问题。请原作者不要追究责任。微笑

首先是前段Ext的代码:

实现下载有两种方式,一种是没经过Action,直接访问下载文件的路径,如:

window.location.href = '文件的服务器路径path';

window.open('文件的服务器路径path');

另外一种是通过Action。  

var downloadForm = document.getElementById("下载文件所需要的参数所在的Form的Id"); 
downloadForm.action = '下载文件请求的url';
downloadForm.method = "POST"; 
downloadForm.submit();

这是直接提交Form。

if(!Ext.fly('downloadAttachFileForm')){
	var frm = document.createElement('form');
	frm.id = 'downloadAttachFileForm'; 
	frm.style.display = 'none'; 
	document.body.appendChild(frm); 
}
Ext.Ajax.Request({
	url: '下载文件请求的url',
	form: Ext.fly('downloadAttachFileForm'),
	method : 'POST',
	params : {},
	isUpload: true,
	success : function(response,options){},
	failure : function(response,options){},
        scope : this
});

这也是提交Form,只不过是用的Ajax。看个人情况,选择用哪种。 直接用Ajax的异步提交,是不可以的。

然后就是后台代码和配置文件了。struts2相关的配置文件就不写了。贴出来下载的方法代码:

/**
	 * 下载附件,这段代码是从网上找的,现在找不到是哪个链接了,如有意见,请联系我表明转载自哪,多谢。
	 * @param fileName 文件名称
	 * @param path 文件所在路径
	 * @param response HttpServletResponse
	 */
	public static void downloadAttachment(String fileName, String path, HttpServletResponse response){  
	    BufferedOutputStream bos = null;  
	    FileInputStream fis = null;  
	    if(null == response){
	    	response = ServletActionContext.getResponse();
	    }
	    if (fileName != null && !"".equals(fileName)) {  
	        try {   
	        	String disposition = "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8");
	        	//注意如果要下载的文件名不做URLEcode处理,项目部署到linux服务器上的话,下载提示框会显示文件名为乱码		
	            response.setContentType("application/x-msdownload;charset=UTF-8");
	            response.setHeader("Content-disposition", disposition);  
	              
	            fis = new FileInputStream(path);  
	            bos = new BufferedOutputStream(response.getOutputStream());  
	            byte[] buffer = new byte[2048];  
	            while(fis.read(buffer) != -1){  
	                bos.write(buffer);  
	            }  
	            bos.flush();
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }finally {  
	            if(fis != null){try {fis.close();} catch (IOException e) {}}  
	            if(bos != null){try {bos.close();} catch (IOException e) {}}  
	        }  
	    }  
	}

这样就实现文件的下载。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值