多个URL文件下载并打包成zip文件

反卷王,因为需要才写了此代码

      • 一、代码实例
      • 二、实例

一、代码实例

// 根据url下载文件打包zip
private void getZip(HttpServletResponse response, String dbUrl)throws Exception{
        //处理文件
        String[] dbUrls = dbUrl.split(",");
        String zipName = new Date().getTime() + ".zip";
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + zipName);
        response.setCharacterEncoding("utf-8");
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (String iUrl : dbUrls) {
                URL url = new URL(iUrl);// 读取url信息
                zipOut.putNextEntry(new ZipEntry(FilenameUtils.getName(iUrl)));// 创建url文件
                InputStream in = new BufferedInputStream(url.openStream());// 读取url文件信息
                zipOut.write(readInputStream(in));//把url文件写入zip中

                zipOut.closeEntry();// 关闭入口
                in.close(); // 关闭连接
            }
        } catch (IOException e) {
            throw new Exception("导出压缩包失败");
        }
        try {
            // 声明一个工作薄  创建新的文件
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("ERROR:Download failed" + e.getMessage());
        }
    }
    
	//根据文件链接把文件下载下来并且转成字节码
    public byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

二、实例

列如:http://localhost:8089/lcyj/information/getZip?dbUrl=url-A,url-B
在这里插入图片描述
多个URL文件下载并打包成zip文件_第1张图片

你可能感兴趣的:(java,zip,java,inputStream,OutputStream,后端)