本文主要是介绍学习记录694@java 多个文件zip压缩后下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实际应用中需要下载多个文件,这个时候最好将这些文件打包成zip,然后再下载。其实非常的简单,只要借助hutool包即可,另外需要对基本的输入输出流了解。
代码
以下代码的基本逻辑是,或者要压缩打包的文件的输入流,然后把这些流打包成zip文件,然后获取这个zip文件的字节数组返回给前端
,并删除这个临时生成的zip文件即可。
import cn.hutool.core.util.ZipUtil;public ResponseEntity downloadZip() throws IOException {String zipName = System.currentTimeMillis()+"压缩文件.zip";String zipPath = "/tmp/"+zipName;// 压缩到的位置File zipFile = new File(zipPath);
//原始的两个文件流List<InputStream> inputStreams = CollUtil.newArrayList();inputStreams.add(new FileInputStream("D:/1713514588576u.jpg"));inputStreams.add(new FileInputStream("D:/1678353151132uu.docx"));
//被压缩的文件在压缩文件中的名字List<String> inputStreamNames = CollUtil.newArrayList();inputStreamNames.add("z1.jpg");inputStreamNames.add("z2.docx");
//hutool的压缩文件工具类ZipUtil.zip(zipFile, inputStreamNames.toArray(new String[inputStreamNames.size()]),inputStreams.toArray(new FileInputStream[inputStreams.size()]));//以上就得到zipFile了,之后就可以任你操作了,比如传给前端、复制、下载等等。BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();zipFile.delete();//删除临时生成的文件HttpHeaders headers = new HttpHeaders();// 设置响应头headers.add("Content-Disposition", "attachment;filename=" + zipName);HttpStatus statusCode = HttpStatus.OK;// 设置响应码ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(buffer, headers, statusCode);return response;}
这篇关于学习记录694@java 多个文件zip压缩后下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!