vue请求springboot接口下载zip文件

说明

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

springboot接口

java 复制代码
@RestController
@RequestMapping("/api/files")
public class FileController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() throws IOException {
        // Assume the ZIP file is located in the resources folder
        File 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);
    }
}
  • 或者是采用传统
java 复制代码
@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调用

html 复制代码
<!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>

执行效果

相关推荐
一 乐19 分钟前
点餐|智能点餐系统|基于java+ Springboot的动端的点餐系统小程序(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·小程序·论文
bitbitDown1 小时前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
liangshanbo12151 小时前
CSS 数学函数完全指南:从基础计算到高级动画
前端·css
码上成长2 小时前
GraphQL:让前端自己决定要什么数据
前端·后端·graphql
冴羽3 小时前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘3 小时前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉3 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
合作小小程序员小小店3 小时前
web网页开发,在线%台球俱乐部管理%系统,基于Idea,html,css,jQuery,jsp,java,ssm,mysql。
java·前端·jdk·intellij-idea·jquery·web
不爱吃糖的程序媛3 小时前
Electron 应用中的系统检测方案对比
前端·javascript·electron
泷羽Sec-静安3 小时前
Less-9 GET-Blind-Time based-Single Quotes
服务器·前端·数据库·sql·web安全·less