栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

前端请求实现文件的批量下载解决办法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

前端请求实现文件的批量下载解决办法

针对文件的批量下载,我们可以通过后端将文件打包成zip,然后通过zip流的方式发送到前端,实现下载

一、后台创建一个解压/压缩 zip文件工具类

1、本功能实现解压功能需要引入ant包,如下

	
		org.apache.ant
		ant
		1.9.7
	

实现压缩zip 功能需要引入zip4j,如下

	
		net.lingala.zip4j
		zip4j
		1.3.2
	

2、zip 解压和压缩工具类如下

public class ZipUtil{

	
	public List batchDecompressionZip (MultipartFile file, string url){
		List list =new ArrayList<>0).
		String filezipName=file.getoriginalFilename():
		File filezip=new File (url);
		filezip.mkdir();
		String filePath=url+"/test/";
		File fileDir=new File(filePath);
		fileDir.mkdir();
		File saveFile=new File(fileDir, filezipName);
		try{
			file.transferTo(saveFile);
			String newFilePath=filePath+filezipName;
			File zipFile=new File(newFilePath);
			//解压保存到本地的zip文件
			list=unZipFiles(zipFile, url);
		]catch (Exception e) {
			e.printstackTrace():
		}
		deleteFile(filePath);
	}

	
	public List unZipFiles (File srcFile, String destDirPath) f
		List list =new ArrayList<>()
		if (!srcFile.exists()) {
			throw new RuntimeException (srcFile.getPath()+"文件不存在");
		}
		//开始解压
		ZipFile zipFile=null;
		try {
			//设置读取编码,window系统执行需要设置编码为“GBK”,linux设置为“UTF-8”
			zipFile=new ZipFile(srcFile,"GBK") ;
			Enumeration entries=zipFile.getEntries();
			while (entries.hasMoreElements()) {
				zipEntry entry= (zipEntry) entries.nextElement();
				//如果是文件夹,就创建一个文件夹
				if (entry.isDirectory()) {
					String dirPath=destDirPathtentry.getName();
					File dir=new File(dirPath);
					dir.mkdir();
				}else{
					//如果是文件,就先创建一个文件,然后用i0流把内容copy过去
					File tartgetFile =new File(destDirBathtentry.getName());
					//确保这个文件夹存在
					list.add(destDirPathtentry.getName()) ;
					if (!tartgetFile.getParentFile().exists()) {
						throw new RuntimeException(tartgetFile.getPath()+"的文文件不存在");
					}
					tartgetFile.createNewfile();
					//将压缩文件中的内容写人到这个文件中
					Inputstream is =zipFile.getInputstream(entry) ;
					FileOutputStream fos=new FileOutputStream(tartgetFile);
					int len;
					byte[] buf=new byte[1024];
					while((len=is.read(buf))!=-1){
						fos.write(buf,0,len);
					}
					is.close();
					fos.close();
				}
			}
		}catch(Exception e){
			e.printStactTrace();
		}finally{
			if(zipFile!=null){
				try{
					zipFile.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return list;
	}
	
	
	public void deletefiles (string filePath){
		File file=new File(filePath);
		if ((!file.exists()) || (!file.isDirectory() )) {
			return;
		}
		String[] temList=file.list();
		File temp=null;
		for (int i=0;i
			if(filePath.endsWith(File.separator)) {
				temp=new File(filePath+temList[i]);
			}else{
				temp=new File(filePath+File.separator+temList[i]);
			}	
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory ()){
				this.deleteFiles(filePath+"\"+temList[i]);
			}
		}
		file.delete();
	}


	
	public void createzipFile (List filePathList, ZipOutputStream zos) {
		FileInputStream fis=null;
		for (string filePath: filePathList) |
			File zip=new File(filePath);
			String fileName=zip.getName();
			try {
				fis=new FileInputStream(filePath) ;
				byte[] buf=new byte[1024*10];
				BufferedInputStream bis=new BufferedInputStream (fis,1024*10);
				zos.putNextEntry(new ZipEntry(fileName) );
				int len=0;
				while ((len=bis.read(buf, 0, buf.length)) !=-1) (
					zos.write(buf, 0, len);
				}
				fis. close() ;
				bis.close();
			]catch (Exception e){
				e.printStackTrace();
			}
		}
	}
}

二、将文件进行压缩然后通过zip流的方式传到前端
RequestMapping(value = "/download", method = RequestMethod.POST)
public void plistDownLoad(HttpServletResponse response) throws Exception {
	 // 此处模拟处理ids,拿到文件下载url
	 List paths = new ArrayList<>();
	 paths.add("C:\Users\E480\Desktop\Study\casul笔记.txt");
	 paths.add("C:\Users\E480\Desktop\Study\config配置中心笔记.txt");
	 paths.add("C:\Users\E480\Desktop\Study\GateWay.txt");
	 ZipUtil zipUtil=new ZipUtil();
	 if (paths.size() != 0) {
		 // 创建临时路径,存放压缩文件
		 String zipFilePath = "D:\workspace-IDEA\zip\我的zip.zip";
		 // 压缩输出流,包装流,将临时文件输出流包装成压缩流,将所有文件输出到这里,打成zip包
		 ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
		 // 循环调用压缩文件方法,将一个一个需要下载的文件打入压缩文件包
		 for (String path : paths) {
		  // 该方法在下面定义
		  zipUtil.createzipFile(paths, zipOut);
	 }
	 // 压缩完成后,关闭压缩流
	 zipOut.close();
	 
	 //拼接下载默认名称并转为ISO-8859-1格式
	 String fileName = new String(("我的压缩文件.zip").getBytes(),"ISO-8859-1");
	 response.setHeader("Content-Disposition", "attchment;filename="+fileName);
	 
	 //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
	 ServletOutputStream outputStream = response.getOutputStream();
	 FileInputStream inputStream = new FileInputStream(zipFilePath);
	 // 如果是SpringBoot框架,在这个路径
	 // org.apache.tomcat.util.http.fileupload.IOUtils产品
	 // 否则需要自主引入apache的 commons-io依赖
	 // copy方法为文件复制,在这里直接实现了下载效果
	 IOUtils.copy(inputStream, outputStream);
	 
	 // 关闭输入流
	 inputStream.close();
	 
	 //下载完成之后,删掉这个zip包
	 File fileTempZip = new File(zipFilePath);
	 fileTempZip.delete();
	 }
}
三、前端用原生js去调用
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.responseType = 'blob';
xhr.onreadystatechange = function(){
   if(xhr.readyState === 4 && xhr.status === 200){
      let res = xhr.response;  //不是responseText。
      let blob = new Blob([res]);   
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = blobUrl;
      a.download = "批量下载.zip";
      a.click();
      URL.revokeObjectURL(blobUrl); // 释放内存
      setMoreAlertVisible(false);
 
      //另一种读取方法
      // var reader = new FileReader(); // 是一个对象,其唯一目的是从 Blob(因此也从 File)                                 
      //对象中读取数据。
      // reader.readAsDataURL(blob); // 转换为base64,可以直接放入a标签href
      // reader.onload = (e) => {
      //     // 转换完成,创建一个a标签用于下载
      //     var a = document.createElement("a");
      //     a.download = "批量下载.zip";
      //     a.href = e.target.result;
      //     document.body.appendChild(a);
      //     a.click();
      //     document.body.removeChild(a);
      // };
    }
}
xhr.send(JSON.stringify(obj));
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号