生成压缩包工具生成代码
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipCompressor {
public static void getZip(String zipName, File zipFile, HttpServletRequest request, HttpServletResponse response, File... files) {
FileOutputStream fos = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
ZipOutputStream zos = new ZipOutputStream(cos)
for (File file : files) {
compressFile(zos, file, file.getName());
String header = request.getHeader(CommonConstants.USER_AGENT).toUpperCase(Locale.ROOT);
zipName = URLEncoder.encode(zipName, CommonConstants.UTF_8);
zipName = zipName.replace("+", "%20");
response.setContentType("text/plain");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Location", zipName);
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
try (FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
FileCopyUtils.copy(bis, bos);
boolean delete = zipFile.delete();
} catch (Exception exception) {
log.error("getZip error: ", exception);
private static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws IOException {
if (!sourceFile.exists()) {
BasicFileAttributes basicFileAttributes = Files.readAttributes(sourceFile.toPath(), BasicFileAttributes.class);
if (basicFileAttributes.isDirectory()) {
File[] fileList = sourceFile.listFiles();
if (fileList.length == 0) {
zos.putNextEntry(new ZipEntry(baseName + File.separator));
for (File file : fileList) {
compressFile(zos, file, baseName + File.separator + file.getName());
ZipEntry zipEntry = new ZipEntry(baseName);
zipEntry.setTime(basicFileAttributes.lastModifiedTime().toMillis());
zos.putNextEntry(zipEntry);
try (FileInputStream fis = new FileInputStream(sourceFile)) {
} catch (Exception exception) {
log.error("输入流关闭异常:", exception);
private static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
int bufferLength = 1024 * 100;
byte[] buffer = new byte[bufferLength];
while ((count = inputStream.read(buffer, 0, bufferLength)) != -1) {
outputStream.write(buffer, 0, count);
应用代码
java
@RequestMapping(value = "/getZip", method = RequestMethod.POST)
public void getZip(@RequestParam("name") String name, HttpServletRequest request, HttpServletResponse response) {
if (StringUtils.isBlank(name)) {
log.info("getZip error: name is not empty");
File file = new File("文件夹路径");
File subFile = new File(file, "子文件夹名称");
String zipName = eventName + ".zip";
File zipFile = FileUtil.createTempFile(eventName, ".zip", true);
ZipCompressor.getZip(zipName, zipFile, request, response, subFile);
} catch (Exception exception) {
log.error("getZip error: ", exception);
FileUtils.forceDelete(file);
} catch (Exception exception) {
log.error("forceDelete error ", exception);
react
jsonSchema2pojo = () => {
const formData = new FormData();
formData.append('name', "名称");
const xhr = new XMLHttpRequest();
xhr.open('POST', apiPrefix + '/getZip', true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
var type = xhr.getResponseHeader('content-type')
var contentDisposition = xhr.getResponseHeader('content-disposition')
if (!filename && contentDisposition) {
var idx = contentDisposition.indexOf('filename=')
filename = decodeURIComponent(contentDisposition.substring(idx + 9))
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename)
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob, {
downloadElement.href = href
downloadElement.download = filename
document.body.appendChild(downloadElement)
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)