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();
    }
}
相关推荐
我的div丢了肿么办4 分钟前
element-plus表格使用:filter-method过滤导致出现无数据
前端·javascript·vue.js
贾公子35 分钟前
AI 内容检测 API 接入实战——异步任务、幂等键与轮询的正确写法
vue.js
星光不问赶路人1 小时前
Vue 项目类型检查:深入理解 vue-tsc --build
前端·vue.js
WeiXin_DZbishe1 小时前
基于springboot装修风格选择系统的设计与开发-计算机毕设【课程设计】77964
java·vue.js·spring boot·后端·python·php·课程设计
雪碧聊技术2 小时前
Vue 一个页面中使用多个同类组件出现“串数据“现象?一个 key 就能解决
vue.js·v-show·一个页面使用多个相同组件·解决数据错乱·v-if、key
十年Java程序媛2 小时前
Java 多线程基础与锁机制详解|进程线程、锁升级、synchronized 与 Lock 对比
java·开发语言·spring boot
Java小卷4 小时前
Vue3 动态表单支持弹框组件
前端·vue.js·低代码
溪语流沙5 小时前
【Web全栈进阶】前端对接新契约:信封解包 + 统一错误处理
前端·vue.js·python·状态模式·fastapi
Q26433650235 小时前
【有源码】基于SpringBoot+Vue的居民健康体检与慢病干预管理系统-面向智慧医疗的体检预约与健康知识服务平台
java·vue.js·spring boot·mysql·毕业设计·javaweb·课程设计
撸串-研究生5 小时前
基于Spring Boot的智慧社区垃圾分类与回收系统的设计与实现【附源码】
spring boot·后端·分类·垃圾分类·社区管理