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>

执行效果

相关推荐
m0_7482517213 分钟前
前端入门之VUE--ajax、vuex、router,最后的前端总结
前端·vue.js·ajax
上等猿16 分钟前
Ajax笔记
前端·笔记·ajax
Amo 672918 分钟前
css 编写注意-1-命名约定
前端·css
GraduationDesign27 分钟前
基于SpringBoot的蜗牛兼职网的设计与实现
java·spring boot·后端
customer0842 分钟前
【开源免费】基于SpringBoot+Vue.JS安康旅游网站(JAVA毕业设计)
java·vue.js·spring boot·后端·kafka·开源·旅游
程序猿online1 小时前
nvm安装使用,控制node版本
开发语言·前端·学习
web Rookie1 小时前
React 中 createContext 和 useContext 的深度应用与优化实战
前端·javascript·react.js
男孩121 小时前
react高阶组件及hooks
前端·javascript·react.js
m0_748251722 小时前
DataOps驱动数据集成创新:Apache DolphinScheduler & SeaTunnel on Amazon Web Services
前端·apache
珊珊来吃2 小时前
EXCEL中给某一列数据加上双引号
java·前端·excel