当前位置: 首页 > 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>

执行效果

在这里插入图片描述

在这里插入图片描述

http://www.lryc.cn/news/418665.html

相关文章:

  • PySide6||QPushButton的QSS样式
  • HarmonyOS鸿蒙应用开发之ArkTS基本语法
  • Web开发-CSS篇-上
  • 在mac上通过 MySQL 安装包安装 MySQL 之后,终端执行 mysql 命令报错 command not found: mysql
  • Unity入门4——常用接口
  • 职业教育云计算实验实训室建设应用案例
  • MySQL-MHA高可用配置及故障切换
  • Sentinel 滑动时间窗口源码分析
  • 猎码安卓APP开发IDE,amix STUDIO中文java,HTML5开发工具
  • 【Deep-ML系列】Linear Regression Using Gradient Descent(手写梯度下降)
  • NVIDIA A100 和 H100 硬件架构学习
  • 企业研发设计协同解决方案
  • iOS 18(macOS 15)Vision 中新增的任意图片智能评分功能试玩
  • 如何实现若干子任务一损俱损--浅谈errgroup
  • 并查集的基础题
  • [论文翻译] LTAChecker:利用注意力时态网络基于 Dalvik 操作码序列的轻量级安卓恶意软件检测
  • HTTPS链接建立的过程
  • 文档控件DevExpress Office File API v24.1 - 支持基于Unix系统的打印
  • IP地址封装类(InetAddress类)
  • 数据库设计规范化
  • 预约咨询小程序搭建教程,源码获取,从0到1完成开发并部署上线
  • leetcode217. 存在重复元素,哈希表秒解
  • QT:QString 支持 UTF-8 编码吗?
  • 我主编的电子技术实验手册(13)——电磁元件之继电器
  • odoo from样式更新
  • Oracle(52)分区表有哪些类型?
  • 大黄蜂能飞的起来吗?
  • 虹科新品 | PDF记录仪新增蓝牙®接口型号HK-LIBERO CL-Y
  • Bytebase 2.22.1 - SQL 编辑器展示更丰富的 Schema 信息
  • SQL Server Management Studio的使用