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();
    }
}
相关推荐
张人玉几秒前
基于 Vue 3 + ECharts + Express + SQLite 的可视化大屏与业务管理系统——YOLOv8 高精度车辆行人检测与计数系统
数据库·vue.js·yolo·sqlite·echarts·express
__log19 分钟前
幂等性设计:从“重复提交“到“稳如磐石“的系统防护
java·开发语言·spring boot
zhangjw3422 分钟前
第35篇:Spring Boot入门:自动配置+快速搭建,简化企业开发
java·spring boot·后端
腻害兔9 小时前
【若依项目-产品经理视角】深度拆解 RuoYi-Vue-Pro 商城模块:从商品管理到交易引擎,50 张表撑起一整套电商系统
java·大数据·vue.js·产品经理·ai编程
sugar__salt16 小时前
Vue3 表单双向绑定与响应式核心 API 技术详解
前端·javascript·vue.js
郝亚军16 小时前
使用Vue 3和Nginx打包和部署Vue.js项目的一般步骤
前端·vue.js·nginx
Java内核笔记16 小时前
告别十亿美元的错误 : Spring Boot 4 空安全 (JSpecify) 实战
java·spring boot·后端
阿懂在掘金18 小时前
企业级命令式弹窗方案:三行代码适配已有 Dialog
前端·vue.js·前端框架
海棠Flower未眠18 小时前
SpringBoot 消息死信队列(荣耀典藏版)
java·数据库·spring boot
YWL19 小时前
OpenLayers + Vue 2 使用指南(01)
前端·javascript·vue.js