vue对后台返回的文件流进行下载

该博客介绍了在Vue中如何处理后台返回的文件流进行下载。通过检查响应头的'content-type'为'application/octet-stream'来确定是文件流,并使用axios封装的request函数进行请求,设置'responseType'为'blob'。然后利用Blob对象创建文件,通过URL.createObjectURL创建下载链接,最后模拟点击下载。
摘要由CSDN通过智能技术生成

//request.js

//对返回数据进行判断,(该项目是因为会对code进行响应拦截,文件流不返回code,所以对code不做判断)

//   if ('application/octet-stream' == response.headers['content-type']) {

 //     return response.data

//    }

download.js

import request from '@/utils/request'

function download(url, fileName, option) {

  var fileName = (fileName || '文件下载').trim()

  //  request 函数是用 axios 封装的请求组件

  return request({

    url: url,

    data: option.data || {},

    method: option.method || 'get',

    responseType: 'blob',

  }).then((data) => {

    saveFile(data, fileName + '.xlsx')

  })

}

function saveFile(data, fileName) {

  let blob = new Blob([data], {

    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

  }); // res就是接口返回的文件流了

  let url = window.URL || window.webkitURL;

  let fileURL = url.createObjectURL(blob);

  let a = document.createElement("a");

  a.href = fileURL;

  a.download = fileName;

  a.target = "_self";

  a.click();

  url.revokeObjectURL(fileURL);

}

export default download

 

student.js 调用

//导出表格

export function export_stu() {

  return download('/students/export_stu',"学生基本信息列表",{'data':{},'method':'get'})

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑞瑞小同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值