vue-axios+springboot实现文件流下载

前端vue代码:

js 复制代码
<template>
  <div class="app-container documentation-container">
    <div>
      <el-button type="primary" @click="downloadFile('test.xlsx')">下载test.xlsx</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Documentation',
  data() {
    return {
    }
  },
  methods: {
    downloadFile(fileName) {
      axios.get('http://localhost:8081/t/downloadFile/' + fileName, {
        responseType: 'blob'
      })
        .then(function (response) {
          // 处理成功情况
          console.log("res:", response);
          if (response.headers['content-Disposition'] || response.headers['content-type'] == 'application/octet-stream') {
            console.log(11);
            let data = response.data;
            console.log('data', data);
            let blob = new Blob([data], {type: 'application/octet-stream'});
            let href = window.URL.createObjectURL(blob);
            let aElement = document.createElement('a');
            aElement.setAttribute('download', fileName);
            aElement.href = href;
            document.body.appendChild(aElement);
            aElement.click();
            document.body.removeChild(aElement);
            window.URL.revokeObjectURL(href); // 释放blob对象
          }
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
        });
    },
  }
}
</script>

后端代码:

java 复制代码
@RestController
@RequestMapping("/t")
public class TestController {

    @CrossOrigin
    @RequestMapping("/downloadFile/{fileName}")
    public void downloadFile(HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException {
        String filePath = "excel/" + fileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
            if (!file.exists()) {
                file.createNewFile();
            }
        }

        //        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString());
        response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }
}
相关推荐
Albert Edison2 小时前
【最新版】IntelliJ IDEA 2025 创建 SpringBoot 项目
java·spring boot·intellij-idea
daols882 小时前
vue vxe-table 自适应列宽,根据内容自适应宽度的2种使用方式
vue.js·vxe-table
行云&流水5 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
三水气象台5 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue
六毛的毛6 小时前
Springboot开发常见注解一览
java·spring boot·后端
盛夏绽放6 小时前
Vue3 中 Excel 导出的性能优化与实战指南
vue.js·excel
开开心心就好7 小时前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑
猴哥源码7 小时前
基于Java+SpringBoot的农事管理系统
java·spring boot
光军oi9 小时前
java微服务(Springboot篇)——————IDEA搭建第一个Springboot入门项目
java·spring boot·微服务
markyankee10110 小时前
Vue 响应式系统全面解析:从基础到高级实践
vue.js