一、具体步骤
- 先获取到要下载的所有文件的绝对路径(在服务器上存放的绝对路径)
- 然后通过ZipOutputStream流将所有的文件循环写到一个临时的zip文件中(这个zip文件可自行命名和确定临时存放位置)
- 通过下载这个zip文件,最后删除这个临时文件
话不多说,上代码:
- 临时文件生成:
/**
* 这里是构建临时的zip文件
**/
public File compressedFileToZip(String name, List<String> filePaths) {
String zipName = name.concat(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))).concat(".zip");
String fileZipPath = System.getProperty("user.dir").concat("/").concat(zipName);
OutputStream os = null;
ZipOutputStream zos = null;
File file = new File(fileZipPath);
try {
if(!file.exists()){
file.createNewFile();
}
os= new FileOutputStream(file);
zos = new ZipOutputStream(os) ;
for (String path : filePaths){
File tempFile = new File(path);
zos.putNextEntry(new ZipEntry(tempFile.getName()));
FileInputStream ins = new FileInputStream(tempFile);
WritableByteChannel writableByteChannel = Channels.newChannel(zos);
FileChannel fileChannel = ins.getChannel();
fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
zos.closeEntry();
fileChannel.close();
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
- 下载操作
public void downloadZip(String name, List<String> filePaths,HttpServletResponse response){
File zipFile = compressedFileToZip(name,filePaths);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
FileInputStream ins = new FileInputStream(zipFile);
WritableByteChannel writableByteChannel = Channels.newChannel(os);
FileChannel fileChannel = ins.getChannel();
fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
fileChannel.close();
response.setCharacterEncoding("UTF-8");
name = URLEncoder.encode(name, "UTF-8");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("iso8859-1")));
response.setContentLength(os.size());
response.setHeader("filename", name);
response.addHeader("Content-Length", "" + os.size());
var outputstream = response.getOutputStream();
os.writeTo(outputstream);
os.flush();
os.close();
outputstream.flush();
outputstream.close();
writableByteChannel.close();
if(zipFile.exists()){
//删除临时文件
zipFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}