最近遇到一个需求,需要在请求接口时,将指定文件夹下的文件进行压缩,然后下载。最初的时候,我使用的是下面的流程进行开发的:
但是,这样的逻辑没有什么问题,但是下载时经常出现压缩包已损坏的问题。尝试了各种方法,一直没有解决。
最后换了一种思路,如下图:
这种的方法是直接遍历文件写入http的响应流,不用在服务器上再创建一个压缩文件,节省了删除文件的操作。而且,没有再出现压缩文件损坏的情况。具体实现代码如下:
@GetMapping("/downloadByPath")
public void fileDownByPath(@RequestParam String sourceFilePath,
HttpServletResponse response) {
try {
String fileName = "result.zip";
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 不存在. <<<<<<");
} else {
ZipOutputStream zos = null;
BufferedInputStream bis = null;
try{
File[] files = sourceFile.listFiles();
zos = new ZipOutputStream(response.getOutputStream());
byte[] buf = new byte[8192];
int len;
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (!file.isFile()) continue;
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
bis = new BufferedInputStream(new FileInputStream(file));
while ((len = bis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
zos.closeEntry();
}
zos.closeEntry();
}catch(Exception ex){
ex.printStackTrace();
}finally {
if(bis != null){
try{
bis.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(zos != null){
try{
zos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载文件失败");
response.setStatus(500);
}
}



