package com.sport.champion.util; import com.sport.common.model.oss.FileInfo; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @Description * @Author lhn * @Version V1.0.0 * @Date 2023/9/5 */ public class BatchDownLoadOssFile { public static void exportZip(List<FileInfo> fileList, HttpServletResponse response,String fileName) throws IOException { Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String timestamp = sdf.format(currentDate); //1.创建zip文件 File zipFile = new File(timestamp+fileName + ".zip"); ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile.toPath())); fileList.forEach(fileInfo -> { ZipEntry entry = new ZipEntry(fileInfo.getName()); try { zos.putNextEntry(entry); zos.write(getFileByte(fileInfo.getUrl())); zos.flush(); } catch (IOException e) { e.printStackTrace(); } }); zos.close(); //2.下载zip downloadZip(zipFile, response); } private static byte[] getFileByte(String url) throws IOException { URL urlConnect = new URL(url); HttpURLConnection con = (HttpURLConnection) urlConnect.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(4 * 1000); InputStream inStream = con.getInputStream(); //通过输入流获取图片数据 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } /** * 下载zip */ private static void downloadZip(File file, HttpServletResponse response) throws IOException { OutputStream outputStream = null; try (FileInputStream fileIn = new FileInputStream(file);) { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8")); response.setContentType("application/octet-stream"); outputStream = response.getOutputStream(); byte[] buffer = new byte[512]; // 缓冲区 int bytesToRead; // 通过循环将读入的Word文件的内容输出到浏览器中 while ((bytesToRead = fileIn.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesToRead); } } catch (IOException ex) { ex.printStackTrace(); } finally { file.delete(); outputStream.close(); } } }
关于下载多个文件并打包成zip的公共方法
最新推荐文章于 2024-07-25 17:24:15 发布