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();
}
}
}
}
}
批量压缩包(打包)下载文件
最新推荐文章于 2022-04-07 10:21:35 发布