@RestController
@RequestMapping(“/file”)
@Slf4j
public class DownloadAndUploadController {
@PostMapping("/downloadBatch")
public void downloadBatch(HttpServletRequest request, HttpServletResponse response, @RequestBody FileDownloadDTO fileDownloadDTO) {
List<String> fileUrl = fileDownloadDTO.getFileUrl();
if (CollectionUtils.isEmpty(fileUrl)) {
System.out.println("文件列表空,无需下载");
return;
}
String[] path = fileUrl.toArray(new String[fileUrl.size()]);
//需要压缩的文件,包括文件地址和文件名
String desPath = fileDownloadDTO.getDesPath();
Path path1 = Paths.get(fileDownloadDTO.getDesPath());
try {
if (!Files.exists(path1)) {
//路径不存在,创建它
Files.createDirectories(path1.getParent());
}
} catch (Exception e) {
e.printStackTrace();
}
File zipFile = new File(desPath);
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
try {
//构造最终压缩包的输出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i < path.length; i++) {
File file = new File(path[i]);
zipSource = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipStream.putNextEntry(zipEntry);
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
//创建读写缓冲区
byte[] buf = new byte[1024 * 10];
while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
zipStream.write(buf, 0, read);
}
}
System.out.println("文件下载到指定位置" + desPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭流
if (null != bufferStream) {
bufferStream.close();
}
if (null != zipSource) {
zipSource.close();
}
if (null != zipStream) {
zipStream.close();
}
System.out.println("流关闭成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}