1.实现服务器上文件批量压缩成zip下载+自定义多个文件夹
package com.fn.szpd.service.impl.zczx;
import com.fn.common.constant.BusinessConstants;
import com.fn.common.core.domain.AjaxResult;
import com.fn.common.exception.base.BaseException;
import com.fn.szpd.domain.SzpdFile;
import com.fn.szpd.service.ISzpdFileService;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RequiredArgsConstructor
public class DownloadZip {
private final ISzpdFileService fileService;
public AjaxResult downloadZip(HttpServletResponse response, Long achievementId) {
try {
if (achievementId == null) {
throw new BaseException("成果id不能为空");
}
SzpdFile szpdFile = new SzpdFile();
szpdFile.setEntityId(achievementId);
szpdFile.setFileType(BusinessConstants.FILE_TYPE_FJ);
szpdFile.setBusinessType(BusinessConstants.BUSINESS_TYPE_SZPD_ZCZX_ACHIEVEMENT);
List<SzpdFile> fileList = fileService.selectSzpdFileList(szpdFile);
if (0 == fileList.size()) {
throw new BaseException("当前成果没有附件");
}
Map<Long, List<SzpdFile>> listMap = fileList.stream().collect(Collectors.groupingBy(SzpdFile::getId));
if (listMap.isEmpty()) {
throw new BaseException("当前成果没有附件");
}
String zipFilePath = System.getProperty("user.dir") + File.separator + "downloadZip" + File.separator;
System.out.println("临时文件路径"+zipFilePath);
File zipFile = new File(zipFilePath);
if (!zipFile.exists()) {
zipFile.mkdirs();
}
String temporaryZipName = zipFilePath + "临时存放.zip";
File zipFiles = new File(temporaryZipName);
if (!zipFiles.exists()) {
zipFiles.createNewFile();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(temporaryZipName));
for (Map.Entry<Long, List<SzpdFile>> entry : listMap.entrySet()) {
writingFilesToZip(zipFilePath, zipOut, entry);
}
zipOut.close();
response.setHeader("Content-Disposition", "attachment;filename=" + new String((achievementId + ".zip").getBytes(), StandardCharsets.ISO_8859_1));
response.setCharacterEncoding("UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(temporaryZipName);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
File fileTempZip = new File(zipFilePath);
deleteDir(fileTempZip);
return AjaxResult.success("下载成功");
} catch (Exception e) {
return AjaxResult.error("下载失败");
}
}
private void writingFilesToZip(String zipFilePath, ZipOutputStream zipOut, Map.Entry<Long, List<SzpdFile>> entry) throws IOException {
for (SzpdFile szpdFile : entry.getValue()) {
downLoadFromUrl(szpdFile.getFileUrl(), zipFilePath, szpdFile.getFileName());
byte[] buf = new byte[2 * 1024];
String srcDir = zipFilePath + szpdFile.getFileName();
File sourceFile = new File(srcDir);
if (844 == entry.getKey()) {
zipOut.putNextEntry(new ZipEntry(this.getFolderName(entry.getKey()) + File.separator + szpdFile.getFileName() + File.separator + sourceFile.getName()));
} else {
zipOut.putNextEntry(new ZipEntry(this.getFolderName(entry.getKey()) + File.separator + sourceFile.getName()));
}
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zipOut.write(buf, 0, len);
}
zipOut.closeEntry();
in.close();
}
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
assert children != null;
for (String child : children) {
boolean success = deleteDir(new File(dir, child));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void downLoadFromUrl(String urlStr, String savePath, String fileName) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
Map<String, List<String>> map = conn.getHeaderFields();
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
fos.close();
inputStream.close();
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
public String getFolderName(Long dataType) {
String result;
if (dataType == 844) {
result = "订单资料";
} else if (dataType == 845) {
result = "零件资料";
} else {
result = "";
}
return result;
}
}
1.实现服务器上文件批量压缩成zip下载不定义文件夹
package com.fn.szpd.service.impl.zczx;
import com.fn.common.constant.BusinessConstants;
import com.fn.common.core.domain.AjaxResult;
import com.fn.common.exception.base.BaseException;
import com.fn.szpd.domain.SzpdFile;
import com.fn.szpd.service.ISzpdFileService;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RequiredArgsConstructor
public class DownloadZip {
private final ISzpdFileService fileService;
public AjaxResult downloadZip(HttpServletResponse response, Long achievementId) {
try {
if (achievementId == null) {
throw new BaseException("成果id不能为空");
}
SzpdFile szpdFile = new SzpdFile();
szpdFile.setEntityId(achievementId);
szpdFile.setFileType(BusinessConstants.FILE_TYPE_FJ);
szpdFile.setBusinessType(BusinessConstants.BUSINESS_TYPE_SZPD_ZCZX_ACHIEVEMENT);
List<SzpdFile> fileList = fileService.selectSzpdFileList(szpdFile);
if (0 == fileList.size()) {
throw new BaseException("当前成果没有附件");
}
String zipFilePath = System.getProperty("user.dir") + File.separator + "downloadZip" + File.separator;
System.out.println("临时文件路径"+zipFilePath);
File zipFile = new File(zipFilePath);
if (!zipFile.exists()) {
zipFile.mkdirs();
}
String temporaryZipName = zipFilePath + "临时存放.zip";
File zipFiles = new File(temporaryZipName);
if (!zipFiles.exists()) {
zipFiles.createNewFile();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(temporaryZipName));
writingFilesToZip(zipFilePath, zipOut, fileList);
zipOut.close();
response.setHeader("Content-Disposition", "attachment;filename=" + new String(("成果文件.zip").getBytes(), StandardCharsets.ISO_8859_1));
response.setCharacterEncoding("UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(temporaryZipName);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
File fileTempZip = new File(zipFilePath);
deleteDir(fileTempZip);
return AjaxResult.success("下载成功");
} catch (Exception e) {
return AjaxResult.error("下载失败");
}
}
private void writingFilesToZip(String zipFilePath, ZipOutputStream zipOut, List<SzpdFile> fileList) throws IOException {
for (SzpdFile szpdFile : fileList) {
downLoadFromUrl(szpdFile.getFileUrl(), zipFilePath, szpdFile.getFileName());
byte[] buf = new byte[2 * 1024];
String srcDir = zipFilePath + szpdFile.getFileName();
File sourceFile = new File(srcDir);
zipOut.putNextEntry(new ZipEntry(sourceFile.getName()));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zipOut.write(buf, 0, len);
}
zipOut.closeEntry();
in.close();
}
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
assert children != null;
for (String child : children) {
boolean success = deleteDir(new File(dir, child));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void downLoadFromUrl(String urlStr, String savePath, String fileName) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
Map<String, List<String>> map = conn.getHeaderFields();
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
fos.close();
inputStream.close();
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}