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 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);
    }
}
  • 或者是采用传统
@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>

执行效果

在这里插入图片描述

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VueSpring Boot中实现文件下载的方法有多种。根据提供的引用内容,我们可以使用文件流的方式来实现。首先,在Vue前端代码中需要定义一个下载文件的方法,可以通过点击按钮触发该方法。 在Vue前端代码中,我们可以使用Element UI等前端框架来创建一个按钮,绑定一个click事件方法,例如: ```html <template> <div> <el-button size="medium" type="success" plain @click="downLoadFile">下载</el-button> </div> </template> ``` 接着,在Vue的JavaScript逻辑部分,使用axios调用后端接口来进行文件下载。具体的JavaScript代码如下所示: ```javascript export default { name: "xxx", data() { return { filePath: 'D:\file\文件名称.pdf', // 文件路径 fileName: '文件名称.pdf', // 文件名称 } }, methods: { // 下载文件方法 downLoadFile() { this.$axios.get("/downFile/downLoadFile", { params: { path: this.filePath, name: this.fileName }, responseType: 'blob' }).then(res => { const blob = new Blob([res.data]); const fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1]; if ('download' in document.createElement("a")) { const link = document.createElement("a"); link.download = fileName; link.style.display = 'none'; link.href = URL.createObjectURL(blob); document.body.appendChild(link); link.click(); URL.revokeObjectURL(link.href); document.body.removeChild(link); } else { navigator.msSaveBlob(blob, fileName); } }) } }, } ``` 在上述代码中,我们通过axios发送GET请求到后端接口`"/downFile/downLoadFile"`,并传递文件的路径和名称作为请求参数。同时,我们指定了`responseType`为`blob`,以便获取到文件的二进制数据。在获取到文件数据后,我们将其保存为Blob对象,并使用创建的下载链接进行文件下载。 请注意,以上代码仅为示例,实际的路径和文件名需要根据具体情况进行修改。此外,需要确保后端接口正确处理文件下载请求,并返回文件的二进制数据。 综上所述,以上代码演示了在VueSpring Boot中实现文件下载的方法,你可以根据需要进行调整和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span> #### 引用[.reference_title] - *1* *2* *3* *4* [vue+springboot使用文件流实现文件下载](https://blog.csdn.net/xc9711/article/details/127485603)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值