package com.project.common.utils.zip;
|
|
import cn.hutool.core.util.ZipUtil;
|
import com.project.common.config.ProjectConfig;
|
import com.project.common.utils.StringUtils;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.URLEncoder;
|
import java.nio.file.Files;
|
import java.nio.file.Paths;
|
import java.util.List;
|
|
@Component
|
@Slf4j
|
public class ZipUtils {
|
|
// 本地资源路径
|
private static String localPath = ProjectConfig.getQrcodePath();
|
|
/**
|
* 下载多个文件转zip压缩包
|
*
|
* @param list 图片数组
|
* @param response 响应
|
*/
|
public static void downloadToZip(List<String> list, List<String> names, HttpServletResponse response)
|
{
|
int i = 0;
|
//如果有附件 进行zip处理
|
if (StringUtils.isNotEmpty(list)) {
|
try {
|
//被压缩文件流集合
|
InputStream[] srcFiles = new InputStream[list.size()];
|
//被压缩文件名称
|
String[] srcFileNames = new String[list.size()];
|
for (String path : list) {
|
//以下代码为获取图片inputStream
|
String s = path.substring(path.lastIndexOf("/"));
|
InputStream ins = Files.newInputStream(Paths.get(localPath + s));
|
//塞入流数组中
|
srcFiles[i] = ins;
|
srcFileNames[i] = names.get(list.indexOf(path))+".png";
|
i++;
|
}
|
response.setCharacterEncoding("UTF-8");
|
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下载.zip", "UTF-8"));
|
//多个文件压缩成压缩包返回
|
ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
}
|
}
|