根據若依系統+minio實現批次下載附件並自動壓縮成zip

枫树湾河桥發表於2024-05-28

效果實現:

分割!!!!

以下程式碼參考於

http://t.csdn.cn/4dUmDwg

話不多說 直接從後端開始

0.首先是pom依賴

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
1.後端Controller

ids和tableName為我業務需要(主要是查詢資料庫的附件表)

/**
* 下載多個檔案轉zip壓縮包
* @param ids
* @param tableName
* @param response
* @throws Exception
*/
@RequestMapping("/dowloadToZip/{ids}/{tableName}")
public void dowloadToZip(@PathVariable Long[] ids,@PathVariable String tableName,HttpServletResponse response) throws Exception {
fileService.dowloadToZip(ids,tableName,response);
}
2.Service實現層

需要各位自己搜尋minio關於下載的程式碼 也就是獲取圖片的inputStream流(因為各自程式碼邏輯不同)


/**
* 下載多個檔案轉zip壓縮包
*
* @param ids
* @param tableName
* @param response
* @throws Exception
*/
@Override
public void dowloadToZip(Long[] ids, String tableName, HttpServletResponse response) throws Exception {
for (Long id : ids) {
int i = 0;
List<Attachment> attachments = attachmentService.attachmentSearch(id.toString(), tableName);
//如果有附件 進行zip處理
if (attachments != null && attachments.size() > 0) {
//被壓縮檔案流集合
InputStream[] srcFiles = new InputStream[attachments.size()];
//被壓縮檔名稱
String[] srcFileNames = new String[attachments.size()];
for (Attachment attachment : attachments) {
//以下程式碼為獲取圖片inputStream
String url = attachment.getUrl();
String[] names = url.split("/");
String name = tableName + "/" + names[names.length - 1];
GetObjectArgs args = GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(name).build();
InputStream inputStream = client.getObject(args);
if (inputStream == null) {
continue;
}
//塞入流陣列中
srcFiles[i] = inputStream;
srcFileNames[i] = attachment.getAttachmentName();
i++;
}
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下載.zip", "UTF-8"));
//多個檔案壓縮成壓縮包返回
ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);
}

}
}
後端到這裡就結束了,主要注意兩個地方

1. ZipUtil是用pom匯入依賴

2. 需要各自補充獲取圖片inputStream的程式碼 然後放入InputStream[]這個陣列中即可

再其次回到前端

前端方面更簡單

1. 找到前端專案的request.js 檢視是否有download方法

如果有這個方法就簡單 沒有的話 各位自己copy吧!

2.找到 button批次下載證件 按鈕 賦值@click="zipDownload" 並實現download程式碼塊


————————————————

版權宣告:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連結和本宣告。

原文連結:https://blog.csdn.net/weixin_44780971/article/details/129985854

相關文章