文件下载。

这一版直接获取到的地址  这个地址就直接可以访问下载的

将多个文件地址 存到压缩包中下载下来

@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();
}
}

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值