前端 使用 js-file-download 下载后端返回的Excel文件

问题描述:调用后端接口,接口返回文件流的形式,

  第一种:window.local.href = 'xx/xx'

  第二种:请求接口 接口返回一段文件流;使用 js-file-download  进行下载;

 js-file-download 使用方式:

  安装

npm install js-file-download --save

  使用:(在需要使用的页面引入)

import fileDownload from 'js-file-download'

  在请求是需要设置下:responseType: 'blob',

  let _that=this
            _that.$axios.get(_that.$api.etmservice+"/export/excel/datamonitor",

                {
                    responseType: 'blob',
                    headers: {
                        'Content-Type': 'application/octet-stream'
                    }
                })
                .then(function(res){
                        fileDownload(res.data,'safa.xlsx')
                })

备注:如果不设置responseType: 'blob', 可能会出现打开文件损坏问题;

  responseType: 'blob',

headers:{
  'Content-Type': 'application/json; application/octet-stream'
},

这俩都指定下就好了

原文地址:https://www.cnblogs.com/lst619247/p/14174547.html