|
|
@@ -7,10 +7,10 @@ import net.lingala.zip4j.model.ZipParameters;
|
|
|
import net.lingala.zip4j.util.Zip4jConstants;
|
|
|
|
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
-import java.io.IOException;
|
|
|
-import java.io.InputStream;
|
|
|
+import java.io.*;
|
|
|
import java.net.HttpURLConnection;
|
|
|
import java.net.URL;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
import java.util.List;
|
|
|
|
|
|
/**
|
|
|
@@ -21,13 +21,36 @@ import java.util.List;
|
|
|
* @Date 2021/8/12 下午7:55
|
|
|
*/
|
|
|
public class File2Zip {
|
|
|
- public static void fileZip(List<FileDto> fileUrls, String zipName, HttpServletResponse response) {
|
|
|
- String zipUrl = "./" + zipName;
|
|
|
+ public static void fileZip(List<FileDto> fileUrls, String zipName, HttpServletResponse response) throws IOException {
|
|
|
+ // zipName的传入格式推荐为: "文件类型" + "_" + userId
|
|
|
+ zipName = zipName + "_" + System.currentTimeMillis() + ".zip";
|
|
|
+ String zipAddr = "./" + zipName;
|
|
|
for (FileDto fileDto : fileUrls) {
|
|
|
- addFileZip(fileDto.getUrl(), fileDto.getName(), zipUrl);
|
|
|
+ addFileZip(fileDto.getUrl(), fileDto.getName(), zipAddr);
|
|
|
}
|
|
|
|
|
|
// 下载
|
|
|
+ File file = new File(zipAddr); // zip所在的路径 /**/**/zipName.zip; fileName = zipName
|
|
|
+ response.setCharacterEncoding("UTF-8");
|
|
|
+ response.setHeader("Content-Disposition",
|
|
|
+ "attachment; filename=" + new String(zipName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
|
|
|
+ response.setContentLength((int) file.length());
|
|
|
+ response.setContentType("application/zip");// 定义输出类型
|
|
|
+ FileInputStream fis = new FileInputStream(file);
|
|
|
+ BufferedInputStream buff = new BufferedInputStream(fis);
|
|
|
+ byte[] b = new byte[4096];// 相当于我们的缓存
|
|
|
+ long k = 0;// 该值用于计算当前实际下载了多少字节
|
|
|
+ OutputStream out = response.getOutputStream();// 从response对象中得到输出流,准备下载
|
|
|
+ // 开始循环下载
|
|
|
+ while (k < file.length()) {
|
|
|
+ int j = buff.read(b, 0, 1024);
|
|
|
+ k += j;
|
|
|
+ out.write(b, 0, j);
|
|
|
+ }
|
|
|
+ out.flush();
|
|
|
+ buff.close();
|
|
|
+ boolean d = file.delete();
|
|
|
+ System.out.println("删除文件: " + d);
|
|
|
}
|
|
|
|
|
|
private static void addFileZip(String fileUrl, String fileName, String zipAddr) {
|
|
|
@@ -55,6 +78,5 @@ public class File2Zip {
|
|
|
e.printStackTrace();
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
}
|
|
|
}
|