这一版直接获取到的地址 这个地址就直接可以访问下载的
将多个文件地址 存到压缩包中下载下来
@GetMapping("/downloadAndZip2")
public void downloadAndZipFiles(HttpServletResponse response) {
// 假设这是你的文件URL列表
List<String> fileUrls = new ArrayList<>();
fileUrls.add("http://127.0.0.1:48080/admin-api/infra/file/4/get/2b83fdb24c253ef79223d5216fdb43b11261add2260ffea0e5f0c453a6fc428d.docx");
fileUrls.add("http://127.0.0.1:48080/admin-api/infra/file/4/get/9da8277a4d5803d3366b15abd1f91337f318e14ac37f9d1f1272230da4035acf.docx");
fileUrls.add("http://127.0.0.1:48080/admin-api/infra/file/4/get/049ad3e393c5efb0fae7811d37da57dcb4711794b1de4e6e60a7f6ef8d743c04.txt");
// 添加更多文件URL
// 设置响应头信息
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"downloaded_files.zip\"");
// 创建一个ZIP输出流
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
for (String fileUrl : fileUrls) {
// 通过URL下载文件内容
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
// 获取文件名,假设文件URL以斜杠分隔,并取最后一个斜杠后的部分作为文件名
String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
// 添加文件到压缩包中
zos.putNextEntry(new ZipEntry(fileName));
// 将文件内容写入到压缩包中
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
// 关闭当前文件的输入流
inputStream.close();
// 关闭当前文件的ZipEntry
zos.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}