首页 |  我的博客 |  查看该博主内容分类 | 

axios下载文件的方法

示例

import Vue from 'vue'

export const downloadBlob = res => {
    const prototype = Vue.prototype
	// prototype.$year、prototype.$month等是全局变量,now结果为字符串,可用任意字符代替
    const now = `${prototype.$year}${prototype.$month}${prototype.$day}${prototype.$hours}${prototype.$minutes}${prototype.$seconds}`
    let filename = `result-file_${now}.xlsx`
    // TODO contentDisposition暂时未能获取到
    const contentDisposition = res.headers['content-disposition']
    if (contentDisposition){
        const match = contentDisposition.match(/filename="(.+)"/)
        if (match && match[1]){
            filename = match[1]
        }
    }
    const blob = new Blob([res.data], {
        type: 'application/vnd.opencmlformat-officedocument.spreadsheetml.sheet'
    })
    const downloadUrl = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = filename
    document.body.appendChild(link)

    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)
}

posted @ 2024-01-02 08:52  Z哎呀  阅读(70)  评论(0)    收藏  举报