Spring Mvc下实现以文件流方式下载文件

        项目中需要对一个点击事件进行下载操作,同时通过点击事件,已经可以从jsp页面获取到需要访问的URL和下载的文件名(数据库获取,jsp页面显示)。点击事件JS如下:

function downloadFile(filePath,fileName){
	
	fileName = fileName.substr(0,fileName.lastIndexOf("."));
	$.ajax({
	    async : false,  
	    cache:false,  
	    type: 'get',
	    dataType : "json",  
	    url: RootPath() + "/checkDownload",//请求的action路径  
	    data:{url:filePath},
	    error: function () {//请求失败处理函数  
	        alert("下载失败");
	    },  
	    success:function(json) { //请求成功后处理函数。
	    	var code = json.code;
	    	if(code) {
	    		window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;
	    	}else {
	    		layer.alert(fileName+' 文件不存在');  
	    	}
	    }  
	});

}


该ajax调用后台(checkDownload)方法,首先判断从该url能否获得指定下载的文件,如果获取不到,方法返回参数code=0,页面弹出“...文件不存在”。

	@RequestMapping("/checkDownload")
	@ResponseBody
	public Result checkDownload(String url,HttpServletResponse response) {
		Result result = Result.createSuccessResult();
		HttpURLConnection conn = null;
		try {
			URL path = new URL(url);
			conn = (HttpURLConnection) path.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			conn.getInputStream();// 通过输入流获取数据
		} catch (IOException ex) {
			result.setCode(0);
			ex.printStackTrace();
		}finally {
			if(conn != null) {
				conn.disconnect();
			}
		}
		return result;
	}
        

如果checkDownload方法中能够正确获得资源,方法返回参数code=1,ajax成功执行:window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;   调用(todownload)方法,传入url和name,执行文件下载。

	@RequestMapping("/todownload")
	@ResponseBody
	public void download(String url, String name, HttpServletResponse response) {
		HttpURLConnection conn = null;
		try {
			File file = new File(url);
			// 取得文件的后缀名。
			String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
			StringBuffer buffername = new StringBuffer(name);
			String filename = buffername.append(".").append(ext).toString();

			URL path = new URL(url);
			conn = (HttpURLConnection) path.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream fis = conn.getInputStream();// 通过输入流获取数据

			byte[] buffer = readInputStream(fis);
			if (null != buffer && buffer.length > 0) {
				// 清空response
				response.reset();
				// 设置response的Header
				response.addHeader("Content-Disposition","attachment;filename="+ new String((filename).getBytes("GBK"),"ISO8859_1"));
				response.addHeader("Content-Length", "" + buffer.length);
				OutputStream toClient = response.getOutputStream();
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		}finally {
			if(conn != null) {
				conn.disconnect();
			}
		}
	}

    /** 
     * 从输入流中获取数据 
     * @param inStream 输入流 
     * @return 
     * @throws Exception 
     */  
	private byte[] readInputStream(InputStream fis) throws IOException {
		 ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        while( (len=fis.read(buffer)) != -1 ){  
	            outStream.write(buffer, 0, len);  
	        }  
	        fis.close();  
	        return outStream.toByteArray();
	} 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值