批量压缩包(打包)下载文件

package com.wangyunjie.test.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/fileUtils/")
public class FileUtils {

	private static String url = "C:/Users/Stefan/Desktop/";//文件以及压缩包缓存地址
	
	@RequestMapping("plDownload")
	public void plDownload(HttpServletRequest request,HttpServletResponse response){
		
		try {
			String zipName = "批量下载.zip";//压缩包名称
			String[] filePaths = {"01vue基础.pdf","vue.js","首页.pptx"};//文件名称
			
			OutputStream out = response.getOutputStream();
			String zipNameL = new String(zipName.getBytes(),"ISO-8859-1");//解决文件下载后中文文件名丢失问题
			
			String zipFilePath = url + zipName;
			for (int i = 0; i < filePaths.length; i++) {
				filePaths[i] = url + filePaths[i];
			}
			//创建压缩文件
			File zip = new File(zipFilePath);
			if(!zip.exists()){
				zip.createNewFile();
			}
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
			zipFile(zos,filePaths);
			response.setContentType("multipart/form-data");
			response.setHeader("Content-disposition", "attachment;filename=" + zipNameL);
			zos.close();
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
			byte[] buff = new byte[bis.available()];
			bis.read(buff);
			out.write(buff);
			bis.close();
			out.flush();
			out.close();
			zip.delete();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void zipFile(ZipOutputStream zos, String[] filePaths) throws IOException {
		// TODO Auto-generated method stub
		for(String filePath : filePaths){
			File inputFile = new File(filePath);
			if(inputFile.exists()){
				if(inputFile.isFile()){
					BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
					zos.putNextEntry(new ZipEntry(inputFile.getName()));
					
					int size = 0;
					byte[] buffer = new byte[1024];
					while((size = bis.read(buffer)) > 0){
						zos.write(buffer, 0, size);
					}
					zos.closeEntry();
					bis.close();
				}
			}
		}
		
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值