spring boot打包压缩下载resources目录下的多个文件

一、打包成zip:ZipUtil

    /**
     * 打包resources目录下的文件夹(不能递归压缩)
     * @param filePath
     * @param zipName
     * @param pattern 通配符,如/**
     */
    @SneakyThrows(IOException.class)
    public static void zipResources(String filePath, String zipName, String pattern) {
        ZipOutputStream zipOutputStream = null;
        try {
            long start = System.currentTimeMillis();
            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipName));
            zipResources(zipOutputStream, zipName, filePath, pattern);
            log.info("文件压缩完毕,耗时:{}", System.currentTimeMillis() - start);
        } finally {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        }
    }

    /**
     * 压缩文件
     * @param out
     * @param zipName
     * @param sourceParentPath
     * @param pattern 通配符
     */
    @SneakyThrows(IOException.class)
    private static void zipResources(ZipOutputStream out, String zipName, String sourceParentPath, String pattern) {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(sourceParentPath + pattern);
        for (Resource resource : resources) {
            log.info("压缩文件:{}", resource.getFilename());
            out.putNextEntry(new ZipEntry(zipName + "/" + resource.getFilename()));
            InputStream inputStream = null;
            try {
                inputStream = resource.getInputStream();
                IOUtils.write(IOUtils.toByteArray(inputStream), out);
                out.flush();
            } catch (Exception e) {
                // 异常后不抛出,继续压缩其他文件
                log.info("压缩文件:{}异常:{}", resource.getFilename(), e);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        }
    }

 二、下载文件:FilUtil

提供下载服务端文件和resource目录下文件


	/**
	 * 将resources目录下的文件打包后传给前端
	 *
	 * @param filePath
	 * @param zipName
	 * @param pattern
	 * @param request
	 * @param response
	 */
	public static void zipAndDownloadResource(String filePath, String zipName, String pattern, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isBlank(zipName)) {
			zipName = "压缩包.zip";
		} else if (!zipName.endsWith(".zip")) {
			zipName = zipName + ".zip";
		}
		// 压缩
		ZipUtil.zipResources(filePath, zipName, pattern);
		// 传输文件
		download(new File(zipName), request, response, true);
	}

	/**
	 * 文件下载
	 *
	 * @param file
	 * @param response
	 * @param isDelete 是否将生成的服务器端文件删除
	 * @throws Exception
	 */
	@SneakyThrows(Exception.class)
	public static void download(File file, HttpServletRequest request, HttpServletResponse response, boolean isDelete) {
		log.info("文件下载:{},{},{}", file.getName(), file.getPath(), file.length());
		download(new FileInputStream(file), file.getName(), file.length(), request, response);
		if (isDelete) {
			file.delete();
		}
	}

	/**
	 * 下载resource目录下的文件
	 *
	 * @param request
	 * @param response
	 * @param filePath 相对resource目录的路径,前面不带 /
	 */
	@SneakyThrows(Exception.class)
	public static void download_resource(HttpServletRequest request, HttpServletResponse response, String filePath) {
		Resource resource = new ClassPathResource(filePath);
		if (resource == null) {
			throw new BusinessException("未找到下载文件");
		}
		InputStream inputStream = resource.getInputStream();
		log.info("文件下载路径:{},文件名:{},文件大小:{}", resource.getURL().getPath(), resource.getFilename(), resource.contentLength());
		download(inputStream, resource.getFilename(), resource.contentLength(), request, response);
	}

	@SneakyThrows(Exception.class)
	private static void download(InputStream inputStream, String fileName, Long contentLength, HttpServletRequest request, HttpServletResponse response) {
		long start = System.currentTimeMillis();

		// 清空response
		response.reset();
		// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
		response.setContentType("application/octet-stream");
		if (regex("Firefox", request.getHeader("User-Agent"))) {
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
		} else {
			response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
		}
		response.addHeader("Content-Length", contentLength.toString());

		OutputStream outputStream = null;
		try {
			outputStream = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[contentLength.intValue()];
			inputStream.read(buffer);
			outputStream.write(buffer);
			outputStream.flush();
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			if (outputStream != null) {
				outputStream.close();
			}
		}
		log.info("文件拷贝完毕,耗时:{}", System.currentTimeMillis() - start);
	}

	private static boolean regex(String regex, String str) {
		Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
		Matcher m = p.matcher(str);
		return m.find();
	}

参考博客

SpringBoot将resources目录资源复制到指定位置

你可能感兴趣的:(java)