vue实现后端接口返回字节流下载文件

1、通过url下载

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

window.location.href = `${location.origin}/template` // 后端提供的地址

通过 window.open(url, '_blank')

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

window.location:当前页跳转,也就是重新定位当前页;

window.open:在新窗口中打开链接;

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

a 标签的 download 属性是 HTML5 标准新增的,作用是触发浏览器的下载操作,这个属性可以设置下载时使用新的文件名称。

前端创建超链接,接收后端的文件流:

axios.get(`/template`, {
        responseType: "blob" //服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
    })
    .then(res => 
        if(!res) return
        let fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].replace(/\"/g, ''))
        const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' }) // 构造一个blob对象来处理数据,并设置文件类型 excel:application/vnd.ms-excel zip: application/zip
          
        if (window.navigator.msSaveOrOpenBlob) { //兼容IE10
            navigator.msSaveBlob(blob, filename)
        } else {
            const href = URL.createObjectURL(blob) //创建新的URL表示指定的blob对象
            const a = document.createElement('a') //创建a标签
            a.style.display = 'none'
            a.href = href // 指定下载链接
            a.download = filename //指定下载文件名
            document.body.appendChild(a);
            a.click() //触发下载
            URL.revokeObjectURL(a.href) //释放URL对象
            document.body.removeChild(a);
        }
        // 这里也可以不创建a链接,直接window.open(href)也能下载
    })
    .catch(err => {
        console.log(err)
    })

请求后台接口时要在请求头上加{responseType: 'blob'};download 设置文件名时,可以直接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并添加到文件。

3、通过 js-file-download 插件

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

猜你喜欢

转载自blog.csdn.net/jiangzhihao0515/article/details/129140776