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();
    }
}
相关推荐
沙蒿同学几秒前
一个人做完一套企业级系统,赚到了第一个 1000 块
vue.js·后端·go
IT枫斗者枫哥4 分钟前
Spring Boot导入返回409,为什么第一行还是入库了?
java·spring boot·后端
SL_staff7 分钟前
四维穿透式齐套判断:JVS-APS在制造计划系统中的技术实现
java·spring boot·python
mldong16 分钟前
管理后台数据国际化:不建翻译表、一列 JSON、后端零改动
vue.js
Eric的技术杂货铺17 分钟前
YsTable 使用:字典管理主从表页面完整实现(列配置、查询、权限按钮、主从联动、增删改查)
前端·vue.js
vipxieliang19 分钟前
ValidX 多租户系统的数据验证方案
java·spring boot
易朵朵19 分钟前
package.json 中的 `vue-router` 详解
前端·vue.js
CopyCode20 分钟前
ref、reactive、toRefs 到底该用哪个?我把三个反例都写了一遍
前端·vue.js
用户425282445675021 分钟前
Vue3 复杂页面状态怎么管?别什么都往 Pinia 里塞了!
vue.js
牧艺25 分钟前
cos-design 4.0:91 个特效组件一次捅成 React / Vue / Web Components / Core
前端·vue.js·web components