当前位置: 首页 > news >正文

vue请求springboot接口下载zip文件

说明

其实只需要按照普通文件流下载即可,以下是一个例子,仅供参考。

springboot接口

@RestController
@RequestMapping("/api/files")
public class FileController {@GetMapping("/download")public ResponseEntity<Resource> downloadFile() throws IOException {// Assume the ZIP file is located in the resources folderFile file = new File("src/main/resources/sample.zip");InputStreamResource resource = new InputStreamResource(new FileInputStream(file));return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=sample.zip").contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length()).body(resource);}
}
  • 或者是采用传统
@GetMapping(value = "/download")public void exportTasks(HttpServletResponse response) throws IOException {try {String filePath = "d:/tmp/aaa.zip";File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException("File not found: " + filePath);}String fileName = FilenameUtils.getName(filePath);// 对中文文件名进行编码String zipFileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "utf-8"));response.setContentType("application/octet-stream;charset=UTF-8");try (InputStream inputStream = new FileInputStream(file);OutputStream outputStream = response.getOutputStream()) {byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}outputStream.flush();}} catch (Exception e) {log.error("下载出错", e);}}

vue调用

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Download ZIP Example</title>
</head>
<body><div id="app"><button @click="downloadZip">Download ZIP</button></div><!-- 引入 Vue --><script src="https://cdn.jsdelivr.net/npm/vue@2"></script><!-- 引入 Axios --><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>new Vue({el: '#app',methods: {async downloadZip() {try {const response = await axios.get('http://localhost:8080/api/files/download', {responseType: 'blob', // 处理二进制数据});const url = window.URL.createObjectURL(new Blob([response.data]));const link = document.createElement('a');link.href = url;link.setAttribute('download', 'sample.zip'); // 下载的文件名document.body.appendChild(link);link.click();link.remove();} catch (error) {console.error('Error downloading the file:', error);}}}});</script>
</body>
</html>

执行效果

在这里插入图片描述

在这里插入图片描述

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【书生大模型实战营第三期 | 入门岛第3关-Git 基础知识】
  • java并发包AtomicInteger类
  • PHP之docker学习笔记
  • uni-app接人腾讯地图
  • 240811-Gradio通过鼠标右键添加事件函数的功能
  • Springboot实现邮箱发送
  • 014集——浮点数值类型——C#学习笔记
  • yarn的淘宝镜像
  • 【代码随想录】有序数组的平方
  • 迪米特法则(LoD)
  • Python 爬取网页水务数据并实现智慧水务前端可视化
  • Linux的常用操作-02
  • 学懂C++(二十二):高级教程——深入理解 C++ 多线程基础理论和概念
  • RAG私域问答场景超级详细方案(第一期方案)[1]:工业级别构建私域问答(知识处理、知识召回排序、搜索问答模块)
  • 算法基础知识——核函数
  • Akka系列(七):Actor持久化之Akka persistence
  • Asm.js的简单介绍
  • - C#编程大幅提高OUTLOOK的邮件搜索能力!
  • express + mock 让前后台并行开发
  • Fastjson的基本使用方法大全
  • JavaScript创建对象的四种方式
  • Java多态
  • JDK 6和JDK 7中的substring()方法
  • leetcode386. Lexicographical Numbers
  • Mysql数据库的条件查询语句
  • ng6--错误信息小结(持续更新)
  • Python实现BT种子转化为磁力链接【实战】
  • ucore操作系统实验笔记 - 重新理解中断
  • Webpack 4x 之路 ( 四 )
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 阿里云应用高可用服务公测发布
  • 开源地图数据可视化库——mapnik
  • 快速体验 Sentinel 集群限流功能,只需简单几步
  • 强力优化Rancher k8s中国区的使用体验
  • 做一名精致的JavaScripter 01:JavaScript简介
  • ​​快速排序(四)——挖坑法,前后指针法与非递归
  • ​创新驱动,边缘计算领袖:亚马逊云科技海外服务器服务再进化
  • #我与Java虚拟机的故事#连载14:挑战高薪面试必看
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (30)数组元素和与数字和的绝对差
  • (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作...
  • (delphi11最新学习资料) Object Pascal 学习笔记---第13章第1节 (全局数据、栈和堆)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (Redis使用系列) Springboot 实现Redis消息的订阅与分布 四
  • (回溯) LeetCode 131. 分割回文串
  • (收藏)Git和Repo扫盲——如何取得Android源代码
  • (一)SvelteKit教程:hello world
  • (原創) 如何優化ThinkPad X61開機速度? (NB) (ThinkPad) (X61) (OS) (Windows)
  • (转)ORM
  • (转载)Linux网络编程入门
  • .a文件和.so文件
  • .net core 实现redis分片_基于 Redis 的分布式任务调度框架 earth-frost
  • .net core 微服务_.NET Core 3.0中用 Code-First 方式创建 gRPC 服务与客户端
  • .Net Core 微服务之Consul(二)-集群搭建
  • .NET 给NuGet包添加Readme