该功能和需求及逻辑在上篇一中已经说明和实现,这是第二种压缩方法,下载同上,只是代码量相对少些,也做下笔记吧。
@GetMapping("/zip")
public void zip(String srcDir, HttpServletRequest request, HttpServletResponse response)throws Exception {
System.out.println("压缩中...");
// 本地资源路径
String localPath = E:/app/uploadPath;
String zipFileName; // 目的地Zip文件
String sourceFileName; //源文件(带压缩的文件或文件夹)
//创建zip输出流
ZipOutputStream out = new ZipOutputStream( new FileOutputStream(localPath+"/test2.zip"));
//创建缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(out);
File sourceFile = new File("E:\\app\\uploadPath\\avatar\\target\\2021");
//调用函数
compress(out,bos,sourceFile,sourceFile.getName());
bos.close();
out.close();
System.out.println("压缩完成");
String contentType = "application/octet-stream";
//下载
download(request, response, localPath+"/test2.zip", "test2.zip");
}
public void compress(ZipOutputStream out,BufferedOutputStream bos,File sourceFile,String base) throws Exception{
//如果路径为目录(文件夹)
if(sourceFile.isDirectory())
{
//取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if(flist.length==0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
{
System.out.println(base+"/");
out.putNextEntry( new ZipEntry(base+"/") );
}
else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
{
for(int i=0;i<flist.length;i++)
{
compress(out,bos,flist[i],base+"/"+flist[i].getName());
}
}
}
else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
{
out.putNextEntry( new ZipEntry(base) );
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int tag;
System.out.println(base);
//将源文件写入到zip文件中
while((tag=bis.read())!=-1)
{
out.write(tag);
}
bis.close();
fos.close();
}
}
/**
* 下载
*/
public static void download(HttpServletRequest request,HttpServletResponse response, String storeName, String contentType,String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String downLoadPath = storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}