1.參考API可見,Java的JDK中提供一個java.util.zip的接口。其壓縮過程主要是通過這兩個接口壓縮文件或者文件夾;
java.util.zip.ZipEntry;
java.util.zip.ZipOutputStream;
2.功能實現
1)頁面請求方式:
window.location.href = "/file/do_upload;
2) web端實現
@RequestMapping("/do_upload")
public void test(HttpServletResponse response, String taskId) throws IOException {
long start = System.currentTimeMillis();
// 獲取附件信息
List<File> files = fileService.listAllFiles(fileId);
//判斷是否為excel類型文件
if(CollectionUtils.isEmpty(files)) {
LOGGER.error("查詢無關聯圖片或者視頻");
} else {
// 設置文件名
formatFileName(response, task);
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(response.getOutputStream());
for (File srcFile : files) {
if (StringUtils.isNotEmpty(srcFile.getFileHbasePath()) && StringUtils.isNotEmpty(srcFile.getFileName())) {
// 下載附件
byte[] bytes = fastDFSService.downloadFile(srcFile.getFileHbasePath());
byte[] buf = new byte[1024];
zos.putNextEntry(new ZipEntry(srcFile.getFileName()));
int len;
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
}
}
long end = System.currentTimeMillis();
System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
設置文件名字和響應信息設置
/** * @methodname formatFileName * @Description {設置響應信息和格式化附件名字} * @author admin */ private void formatFileName(HttpServletResponse response) throws UnsupportedEncodingException { String fileName = "附件文字"; Long actualEndTime = new Date().getTime(); fileName += actualEndTime + ".zip"; // 獲取瀏覽器信息 if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1"); } else { // 處理中文文件名的問題 fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); fileName = new String(fileName.getBytes("UTF-8"), "GBK"); } // 清除首部的空白行 response.reset(); // 設置Response容器的編碼 response.setCharacterEncoding("UTF-8"); // 不同類型的文件對應不同的MIME類型 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment; filename="+fileName); }
參考原文地址:
獲取游覽器信息:https://blog.csdn.net/w410589502/article/details/73163383
壓縮文件:https://blog.csdn.net/yunyingxiaoyi/article/details/103407789
