java批量下載生成zip壓縮包的思路詳解
設(shè)計(jì)思路:
1.本地先創(chuàng)建一個(gè)zip文件
2.將批量下載的文件依次放入zip文件中
3.將zip文件返回給前端
//一、本地先生成zip文件
//要批量下載的文件id數(shù)組
String[] ids = new String[] {"1","2"}
byte[] buffer = new byte[1024];
//創(chuàng)建zip
String localZipFile = "D:/temp/test.zip" ;
if(!new File(localZipFile).exists()){
new File(localZipFile).mkdirs();
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(localZipFile));
//依次獲取批量下載的文件
for(int i =0; i<ids.length;i++){
//設(shè)置壓縮包內(nèi)的文件的字符編碼,不然文件名可能變成亂碼(用戶為windows系統(tǒng))
out.setEncoding("GBK");
//從數(shù)據(jù)庫(kù)中獲取文件的路徑和文件名,并放入zip文件中
String fileId = ids[i];
Map<String,Object> map =exportManagerService.getFjInfo(fileId);
FileInputStream inStream = new FileInputStream(new File(map.get("path").toString()));
out.putNextEntry(new ZipEntry(map.get("name").toString()));
int len;
//讀入需要下載的文件的內(nèi)容,打包到zip文件
while ((len = inStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
inStream.close();
}
out.close();
this.downFile(response,"D:/temp","test.zip");
//二、將本地zip返回給前端
private void downFile(HttpServletResponse response,String FilePath, String str) {
Map m = new HashMap();
try {
String path = FilePath +"/"+ str;
File file = new File(path);
if (file.exists()) {
InputStream ins = new FileInputStream(path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到緩沖流里面
OutputStream outs = response.getOutputStream();// 獲取文件輸出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.addHeader("content-disposition", "attachment;filename="
+ java.net.URLEncoder.encode(str, "UTF-8"));
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 開始向網(wǎng)絡(luò)傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這里一定要調(diào)用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
}
} catch (IOException e) {
m.put("code", "-1");
m.put("text", "附件下載出錯(cuò):" + e.getMessage());
e.printStackTrace();
}
}補(bǔ)充:
java 批量下載文件 打包成zip包
創(chuàng)建DownLoadUrlStream承載數(shù)據(jù)
import lombok.Data;
import java.io.InputStream;
@Data
public class DownLoadUrlStream {
//文件地址 比如/123/234/1.txt
private String url;
//文件流
private InputStream stream;
}創(chuàng)建工具類,進(jìn)行zip包壓縮
import com.valid.util.view.DownLoadUrlStream;
import com.valid.util.view.DownLoadUrlString;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Component
public class DownloadUtils {
/**
*
* @param downLoadUrlStreams 文件信息 地址 流
* @param zipName 壓縮包名稱
* @param response
* @throws IOException
*/
public void downloadFolder(List<DownLoadUrlStream> downLoadUrlStreams,String zipName, HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(zipName,"UTF-8") + "\"");
Set<String> paths = new HashSet<>(); // 用于記錄已經(jīng)添加到壓縮文件中的目錄
try {
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (DownLoadUrlStream file : downLoadUrlStreams) {
String virtualPath = file.getUrl().substring(1);
String[] pathArray = virtualPath.split("/");
//構(gòu)建文件的目錄結(jié)構(gòu)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pathArray.length - 1; i++) {
sb.append(pathArray[i]).append("/");
String folderPath = sb.toString();
if (!paths.contains(folderPath)) { // 如果該目錄還未被添加到壓縮文件中,則添加目錄
ZipEntry folderEntry = new ZipEntry(folderPath);
zipOut.putNextEntry(folderEntry);
zipOut.closeEntry();
paths.add(folderPath); // 將新添加的目錄記錄到集合中
}
}
ZipEntry entry = new ZipEntry(virtualPath);
zipOut.putNextEntry(entry);
//將文件流寫入文件中
InputStream inputStream = file.getStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
zipOut.write(buffer, 0, len);
}
inputStream.close();
zipOut.closeEntry();
}
zipOut.flush();
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}封裝數(shù)據(jù),調(diào)用方法即可
到此這篇關(guān)于java批量下載生成zip壓縮包的思路詳解的文章就介紹到這了,更多相關(guān)java批量下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Maven打包時(shí)包含資源文件和源碼到j(luò)ar的方法
這篇文章主要介紹了使用Maven打包時(shí)包含資源文件和源碼到j(luò)ar的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
Spring?boot配置綁定和配置屬性校驗(yàn)的方式詳解
這篇文章主要介紹了Spring?boot配置綁定和配置屬性校驗(yàn),SpringBoot 提供了2 種方式進(jìn)行配置綁定,即使用 @ConfigurationProperties 注解和使用 @Value 注解,需要的朋友可以參考下2022-05-05
ShardingSphere數(shù)據(jù)分片算法及測(cè)試實(shí)戰(zhàn)
這篇文章主要為大家介紹了ShardingSphere數(shù)據(jù)分片算法及測(cè)試實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
解決maven常見錯(cuò)誤:Dependency is duplicated in
這篇文章主要介紹了解決maven常見錯(cuò)誤:Dependency is duplicated in file(s):問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
Java 基礎(chǔ)之NIO 學(xué)習(xí)詳解
這篇文章主要介紹了java基礎(chǔ)之NIO介紹及使用,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-09-09
Mybatis分頁(yè)插件PageHelper的使用詳解
這篇文章主要介紹了Mybatis分頁(yè)插件PageHelper的相關(guān)資料,該插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數(shù)據(jù)庫(kù)分頁(yè)需要的朋友可以參考下2016-12-12
LinkedList學(xué)習(xí)示例模擬堆棧與隊(duì)列數(shù)據(jù)結(jié)構(gòu)
這篇文章主要介紹了LinkedList學(xué)習(xí)示例,模擬一個(gè)堆棧與隊(duì)列數(shù)據(jù)結(jié)構(gòu),大家參考使用吧2014-01-01

