欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java批量下載生成zip壓縮包的思路詳解

 更新時(shí)間:2024年01月31日 17:20:16   作者:夏夜里的晚風(fēng)。  
這篇文章主要介紹了java批量下載生成zip壓縮包的思路詳解,設(shè)計(jì)思路大概是本地先創(chuàng)建一個(gè)zip文件,將批量下載的文件依次放入zip文件中,將zip文件返回給前端,本文結(jié)合實(shí)例代碼講解的非常詳細(xì),需要的朋友可以參考下

設(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)文章

最新評(píng)論