后端接口返回二进制流压缩文件vue前端处理

//_downloadUserTpl为封装好的接口
downloadLink() {
      _downloadUserTpl({
        responseType: "blob",
      }).then((res) => {
        let elink = document.createElement("a");
        elink.download = "cert.zip";
        elink.style.display = "none";
        let blob = new Blob([res.data], {
          type: "application/x-zip-compressed",
        });
        elink.href = URL.createObjectURL(blob);

        document.body.appendChild(elink);
        elink.click();

        document.body.removeChild(elink);
      });
    },

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Vue+SpringBoot批量下载的实现方法: 1.前端Vue代码: ```html <template> <div> <el-button type="primary" @click="downloadAll">批量下载</el-button> </div> </template> <script> export default { methods: { downloadAll() { // 获取需要下载的文件路径列表 const paths = ['path1', 'path2', 'path3']; // 发送POST请求到后端下载接口 this.$axios.post('/downloadAll', paths, { responseType: 'blob' }).then(res => { // 将二进制转换为文件并下载 const blob = new Blob([res.data], { type: 'application/zip' }); const fileName = 'download.zip'; if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } }); } } } </script> ``` 2.后端SpringBoot代码: ```java @RestController @RequestMapping("/download") public class DownloadController { @PostMapping("/downloadAll") public void downloadAll(@RequestBody List<String> paths, HttpServletResponse response) throws IOException { // 创建临时文件夹 File tempDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); tempDir.mkdirs(); // 将需要下载的文件复制到临时文件夹中 for (String path : paths) { File file = new File(path); FileUtils.copyFileToDirectory(file, tempDir); } // 压缩临时文件夹中的文件 File zipFile = new File(System.getProperty("java.io.tmpdir"), "download.zip"); ZipUtil.pack(tempDir, zipFile); // 设置响应头 response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8")); // 将压缩后的文件写入响应中 try (InputStream in = new FileInputStream(zipFile); OutputStream out = response.getOutputStream()) { IOUtils.copy(in, out); out.flush(); } // 删除临时文件夹和压缩文件 FileUtils.deleteDirectory(tempDir); FileUtils.deleteQuietly(zipFile); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值