实际应用中需要下载多个文件,这个时候最好将这些文件打包成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;}