一、文件打包为zip
public void zip(List<File> fileList,String zipFileName) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
ZipOutputStream zipOutputStream = null;
BufferedInputStream bufferInputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("C:/temp/" + zipFileName));
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
byte[] bufs = new byte[1024 * 10];
for (File file : fileList) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
fileInputStream = new FileInputStream(file);
bufferInputStream = new BufferedInputStream(fileInputStream, 1024 * 10);
int read = 0;
while ((read = bufferInputStream.read(bufs, 0, 1024 * 10)) != -1) {
zipOutputStream.write(bufs, 0, read);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferInputStream != null) {
bufferInputStream.close();
}
if (zipOutputStream != null) {
zipOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、下载zip包
public void downloadZip(HttpServletResponse response, String zipFileName) {
File zipFile = new File("C:/temp/" + zipFileName);
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
FileInputStream fileInputStream = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
fileInputStream = new FileInputStream(zipFile);
byte[] bufs = new byte[1024 * 10];
int read = 0;
while ((read = fileInputStream.read(bufs, 0, 1024 * 10)) != -1) {
outputStream.write(bufs, 0, read);
}
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
File file = new File("C:/temp/" + zipFileName);
file.delete();
if (fileInputStream != null) {
fileInputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、下载接口
@GetMapping("/downloadZip")
@ApiOperation("下载zip")
public void downloadZip(HttpServletResponse response) {
downloadService.downloadZip(response);
}