zip包文件下载
记录:
Util
public class ZipUtil {
public static byte[] createZip(String sourcePath) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//将目标文件打包成zip导出
File file = new File(sourcePath);
writeZip(zip,file,"");
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
public static byte[] createZipByFileList(List<String> fileNames) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//将目标文件打包成zip导出
for (int i = 0; i < fileNames.size(); i++) {
File file = new File(fileNames.get(i));
writeZip(zip,file,"");
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
private static void writeZip(ZipOutputStream zip,File file, String parentPath ) throws Exception {
if (file.exists()) {
if (file.isDirectory()) {//处理文件夹
File[] files = file.listFiles();
parentPath += file.getName() + File.separator;
if (files.length != 0) {
for (File f : files) {
writeZip(zip,f, parentPath);
}
} else { //空目录则创建当前目录
zip.putNextEntry(new ZipEntry(parentPath));
}
} else {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(parentPath+file.getName());
zip.putNextEntry(entry);
zip.write(FileUtils.readFileToByteArray(file));
IOUtils.closeQuietly(bis);
zip.flush();
zip.closeEntry();
}
}
}
}
Controller
@GetMapping("/download")
public void downloadFile(HttpServletResponse response, @RequestParam("orderDetailId") Integer orderDetailId) throws IOException {
List<OrderDetailFileEntity> fileUrlByOrderDeatilId = orderDetailFileService.getFileUrlByOrderDeatilId(orderDetailId);
//该明细下有文件
if (null != fileUrlByOrderDeatilId && fileUrlByOrderDeatilId.size()!= 0 ) {
ArrayList<String> fileNames = new ArrayList<>();
for (OrderDetailFileEntity fileUrlAndName : fileUrlByOrderDeatilId) {
String fileFtpUrl = fileUrlAndName.getFileFtpUrl();
String fileName = fileUrlAndName.getFileName();
fileNames.add(fileFtpUrl + File.separator + fileName);
}
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件下载.zip", "UTF-8"));
try {
// byte[] zip1 = ZipUtil.createZip(fileName);
//将目标文件打包成zip导出
byte[] zip1 = ZipUtil.createZipByFileList(fileNames);
response.getOutputStream().write(zip1);
} catch (Exception e) {
e.printStackTrace();
}
}else{
throw new RRException("该明细下没有文件,请确认后重试!");
}
}