批量下载文件

后端
1、拿到数组id
2、拿到要批量下载的路径
3、读取要批量下载的路径,写入临时路径
4、下载临时路径目录下所有文件
5、删除临时路径

@RequestMapping(value="/downloadMany.ajax")
	public void downloadMany(T9c_employee_papersDTO t9c_employee_papersDTO,HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.setCharacterEncoding("UTF-8");
		OutputStream  fileOut = null ;
		//拿到数组id
		String[] ids = t9c_employee_papersDTO.getSel();
		String tempZipname = "";
		String filepath ="";
		String temp_path="";
		for(String id : ids) {
			t9c_employee_papersDTO.setId(id);
			if(!StringUtils.isEmpty(id)){//交付阶段压缩包
				//拿到该证件的整条信息
				t9c_employee_papersDTO=t9c_employee_papersService.getT9c_employee_papaersById(t9c_employee_papersDTO);
				//路径信息
				filepath=t9c_employee_papersDTO.getAddress();
				//临时路径,papers替换papers/temp/userid+姓名
				temp_path=filepath.replace("papers", "papers/temp/"+t9c_employee_papersDTO.getUserid()+t9c_employee_papersDTO.getUsername());
				//截取temp后的路径,图片之前的路径
				String temp_dir = temp_path.substring(0,temp_path.lastIndexOf("\\"));
				//创建temp临时路径
				File dir = new File(temp_dir);
				if(!dir.exists()) {
					dir.mkdirs();
				}
				//把文件放入路径之下
				File file=new File(temp_path);
				if(!file.exists()) {
					file.createNewFile();
				}
		             
				//路径下文件为输出流
				fileOut  = new FileOutputStream(file);
				//定义输入流
				InputStream inp=null;
				try {
					//读取路径下文件,输出流写入
					inp = new FileInputStream(filepath);
					byte[] bytes = new byte[4096];
			        int length;
			        while ((length = inp.read(bytes)) > 0){
			        	fileOut.write(bytes, 0, length);
			        }
				} finally {
					if(null != inp){
						inp.close();
						fileOut.close();
					}
				}
			}
		}
		try {
			tempZipname="certificaty_info.ZIP";//压缩文件名
			ZipUtils zipUtils = new ZipUtils();
			//获得压缩到哪个路径
			String s=temp_path.substring(0,temp_path.indexOf("temp")+4);
			zipUtils.zip(tempZipname, s, response);
			File file =new File(s);
			deleteFile(file);
		}catch (Exception e) {
			logger.info(e.getMessage());
		}
	}

递归删除临时目录

public static void deleteFile(File file) {
		if(file.exists()) {//判断路径是否存在
			if(file.isFile()){//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。 
				file.delete();
			}else{//不是文件,对于文件夹的操作
				//保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
				File[] listFiles = file.listFiles();//listFiles方法:返回file路径下所有文件和文件夹的绝对路径
				for (File file2 : listFiles) {
					/*
					 * 递归作用:由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
					 *    注意:此时的文件夹在上一步的操作之后,里面的文件内容已全部删除
					 *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
					 */
					deleteFile(file2);
				}
			}
			file.delete();
		}else {
			System.out.println("该file路径不存在!!");
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值