【记录】文件批量下载
作者:互联网
实现
@Override
public void getBatch(HttpServletRequest request, HttpServletResponse response, PdfBatchDTO pdfDTO)
throws Exception {
//存放文件路径
List<String> filenames = new ArrayList<>();
filenames.add("D:\b.pdf");
filenames.add("D:\文档.docx");
if (!ObjectUtils.isEmpty(filenames)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String fileAdd = sdf.format(new Date());
String inputPath = realPath + File.separator + fileAdd + File.separator;
//生成压缩包
String fileName = "下载.zip";
String rarPath = inputPath + File.separator + File.separator + fileName;
File file = new File(rarPath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fOutputStream = new FileOutputStream(file);
ZipOutputStream zoutput = new ZipOutputStream(fOutputStream);
for (String filename : filenames) {
fileToZip(filename, zoutput);
}
zoutput.close();
//拼接下载默认名称并转为ISO-8859-1格式
String fileName2 = new String(("我的压缩文件.zip").getBytes(), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attchment;filename=" + fileName2);
//该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(rarPath);
// 如果是SpringBoot框架,在这个路径
// org.apache.tomcat.util.http.fileupload.IOUtils产品
// 否则需要自主引入apache的 commons-io依赖
// copy方法为文件复制,在这里直接实现了下载效果
IOUtils.copy(inputStream, outputStream);
// 关闭输入流
inputStream.close();
//下载完成之后,删除所有文件
deleteDir(inputPath);
}
}
工具类
//删除文件加下所有内容
public static void deleteDir(String path) {
File file = new File(path);
if (!file.exists()) {//判断是否待删除目录是否存在
System.err.println("The dir are not exists!");
return;
}
String[] content = file.list();//取得当前目录下所有文件和文件夹
for (String name : content) {
File temp = new File(path, name);
if (temp.isDirectory()) {//判断是否是目录
deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
temp.delete();//删除空目录
} else {
if (!temp.delete()) {//直接删除文件
System.err.println("Failed to delete " + name);
}
}
}
return;
}
标签:file,String,temp,记录,filenames,File,new,文件批量,下载 来源: https://blog.csdn.net/weixin_46697618/article/details/121695241