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>

执行效果

相关推荐
Highcharts1 分钟前
用Highcharts如何动态向一个序列添加点-示列讲解
前端
weixin_4316004412 分钟前
做 Agent 会用到的 Node API(4):取消与 AbortController
前端·学习·ai·agent·ai编程
用户21816970493025 分钟前
Flutter(十)Container Center Align
前端
xiaoqiMikko33 分钟前
Spring Cloud Config 这个 CVE 的补丁,Maven Central 上根本没有
java·spring boot
无人生还34 分钟前
从 Vue3 到 React · 快速上手系列第 12 篇:并发特性与性能优化
前端·vue.js·react.js
小p36 分钟前
nextjs学习9: Next.js 渲染与缓存
前端·后端
乘风gg37 分钟前
AI 时代,你的编程能力在第几层?我敢说,大多数人卡在第一层
前端·ai编程·claude
东风破_38 分钟前
React Router v7 实战:用路由配置、懒加载与嵌套路由搭建一个完整的 SPA
前端
引山洪0838 分钟前
Babylon.js 8.x 中文文档整理——Node篇 (上)
前端·webgl
用户31268748772039 分钟前
Spring Boot 配置体系到底怎么加载的?从 application.yml 到 @Conditional 的全链路拆解
java·spring boot