批量下载文件,打包成zip压缩包

批量下载文件,用程序打成zip压缩包在下载

前台传来要下载的url数组

@RequestMapping(value = "/download",method = RequestMethod.POST)  
public void download(HttpServletResponse response,String [] filePathList) throws IOException{  
	// 通过response对象获取OutputStream流  
	OutputStream os = response.getOutputStream();  
	//获取zip的输出流  
        ZipOutputStream zos = new ZipOutputStream(os);  
	//定义输入流  
        BufferedInputStream bis = null;  
  
	try {  
		//循环url数组  
		for (String path : filePathList) {  
  			//通过url地址获取连接  
			URL url = new URL(path);  
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  
			//设置超时间为3秒     
			conn.setConnectTimeout(3*1000);    
  
			//防止屏蔽程序抓取而返回403错误    
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");    
			conn.setRequestMethod("GET");  
			conn.connect();  
  
			//通过连接得到输入流    
			InputStream inputStream = conn.getInputStream();   
  
			//设置压缩后的zip文件名  
			String sourceFilePath = "zip.zip";  
  
			//设置content-disposition响应头控制浏览器弹出保存框,若没有此句则浏览器会直接打开并显示文件。  
			//中文名要经过URLEncoder.encode编码,否则虽然客户端能下载但显示的名字是乱码  
  
       			response.setHeader("content-disposition", "attachment;filename="   
			+ URLEncoder.encode(sourceFilePath, "UTF-8"));  
  
			byte[] buf = new byte[8192];  
        		int len = 0;  
  
        		//创建ZIP实体,并添加进压缩包    
        		ZipEntry zipEntry = new ZipEntry(fileName);    
        		zos.putNextEntry(zipEntry);    
        		bis = new BufferedInputStream(inputStream, 1024*10);    
       			while ((len = bis.read(buf)) > 0) {  
        		//使用OutputStream将缓冲区的数据输出到客户端浏览器  
        		zos.write(buf, 0, len);  
        		}    
		}  
	} catch (Exception e) {  
		e.printStackTrace();  
	}finally{  
		if(null != zos) zos.close();  
		if(null != bis) bis.close();  
	}  
}            



猜你喜欢

转载自blog.csdn.net/xjiuge/article/details/78499853