接上篇,有导入也就有导出需要。

要求导出excel文件。当点击下载模板或下载反馈后果,axios发动后端接口申请,返回的数据获取 response 时呈现乱码,如图:

现总结如下几种解决办法。

1、通过 url 下载

即后端提供文件的地址,间接应用浏览器去下载

  • 通过 window.location.href = 文件门路 下载

    window.location.href = `${location.origin}/operation/ruleImport/template`
  • 通过 window.open(url, '_blank')

    window.open(`${location.origin}/operation/ruleImport/template`)

这两种应用办法的不同:

  • window.location:当前页跳转,也就是从新定位当前页;只能在网站中关上本网站的网页。
  • window.open:在新窗口中关上链接;能够在网站上关上另外一个网站的地址。

2、通过 a 标签的 download 属性联合 blob 构造函数下载

a 标签的 download 属性是 HTML5 规范新增的,作用是触发浏览器的下载操作而不是导航到下载的url,这个属性能够设置下载时应用新的文件名称。

前端创立超链接,接管后端的文件流:

axios.get(`/operation/ruleImport/template`, {        responseType: "blob" //服务器响应的数据类型,能够是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'    })    .then(res =>         if(!res) return        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 结构一个blob对象来解决数据,并设置文件类型                if (window.navigator.msSaveOrOpenBlob) { //兼容IE10            navigator.msSaveBlob(blob, this.filename)        } else {            const href = URL.createObjectURL(blob) //创立新的URL示意指定的blob对象            const a = document.createElement('a') //创立a标签            a.style.display = 'none'            a.href = href // 指定下载链接            a.download = this.filename //指定下载文件名            a.click() //触发下载            URL.revokeObjectURL(a.href) //开释URL对象        }        // 这里也能够不创立a链接,间接window.open(href)也能下载    })    .catch(err => {        console.log(err)    })

注:申请后盾接口时要在申请头上加{responseType: 'blob'};download 设置文件名时,能够间接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并增加到文件。

3、通过 js-file-download 插件

  • 装置:npm install js-file-download --S
  • 应用

    import fileDownload from 'js-file-download'axios.get(`/operation/ruleImport/template`, {        responseType: 'blob' //返回的数据类型    })    .then(res => {        fileDownload(res.data, this.fileName)    })