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>

执行效果

相关推荐
阿幸软件杂货间几秒前
谷歌浏览器(Google Chrome)136.0.7103.93便携增强版|Win中文|安装教程
前端·chrome
繁依Fanyi30 分钟前
Animaster:一次由 CodeBuddy 主导的 CSS 动画编辑器诞生记
android·前端·css·编辑器·codebuddy首席试玩官
想起你的日子38 分钟前
Android studio 实现弹出表单编辑界面
java·前端·android studio
LuckyLay2 小时前
Vue百日学习计划Day9-15天详细计划-Gemini版
前端·vue.js·学习
源码方舟3 小时前
SpringBoot + Shiro + JWT 实现认证与授权完整方案实现
java·spring boot·后端
大得3696 小时前
electron结合vue,直接访问静态文件如何跳转访问路径
javascript·vue.js·electron
热河暖男6 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
水银嘻嘻8 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
小嘟嚷ovo8 小时前
h5,原生html,echarts关系网实现
前端·html·echarts
十一吖i9 小时前
Vue3项目使用ElDrawer后select方法不生效
前端