导出ZIP文件
比较常用的两种:
导出图片压缩文件,导出excel压缩文件;
导出思路:需要导出的文件转存为byte数组保存到Map,然后遍历压缩成zip
需要引入jar:
<!-- 导出zip格式文件 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.12</version>
</dependency>
一、导出图片压缩文件
/**
* 图片到byte数组
* @param imageUrl
* @param imageName
* @return
*/
public static byte[] imgageToByte(String imageUrl, String imageName) throws IOException {
File imageFile = new File(imageUrl + File.separator + imageName);
if(!imageFile.exists()){
log.error("---imgageToByte--imageUrl([{}])--is--null", imageUrl);
return null;
}
// return Files.readAllBytes(imageFile.toPath()); // 不推荐
FileInputStream fis = new FileInputStream(imageFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
byte[] imagetByte = bos.toByteArray();
fis.close();
bos.close();
return imagetByte;
}
/**
* 输出zip格式文件
* @param response
* @param zipName zip文件名称
* @param zipMap 压缩的图片信息
*/
public static void fileTozip(HttpServletResponse response, String zipName, Map<String, byte[]> zipMap) {
try{
response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
ServletOutputStream outputStream = response.getOutputStream();
ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
zipOutputStream.setUseZip64(Zip64Mode.AsNeeded);
for(String fileName: zipMap.keySet()){
ArchiveEntry archiveEntry = new ZipArchiveEntry(fileName);
zipOutputStream.putArchiveEntry(archiveEntry);
byte[] fileByte = zipMap.get(fileName);
zipOutputStream.write(fileByte);
zipOutputStream.closeArchiveEntry();
}
zipOutputStream.close();
outputStream.close();
}catch (Exception e){
log.error("fileTozip error:[{}]", ExceptionUtils.getStackTrace(e));
}
}
二、导出excel压缩文件
把csv文件转为byte数组,然后再通过fileTozip方法输出zip文件即可
/**
* 写CSV并转换为字节流
* @param headers 表头
* @param cellList 表数据
* @return
*/
public static byte[] writeCsvAfterToBytes(String[] headers,List<Object[]> cellList) {
byte[] bytes = new byte[0];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, Charset.forName("UTF-8"));
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
CSVPrinter csvPrinter = null;
try {
//创建csvPrinter并设置表格头
csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader(headers));
//写数据
csvPrinter.printRecords(cellList);
csvPrinter.flush();
bytes = byteArrayOutputStream.toString("UTF-8").getBytes();
} catch (IOException e) {
log.error("writeCsv IOException:{}", e.getMessage(), e);
} finally {
try {
if (csvPrinter != null) {
csvPrinter.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
log.error("iostream close IOException:{}", e.getMessage(), e);
}
}
return bytes;
}