vue使用blob下载文件

//封装好的api
export function downFile(url, parameter) {
    return axios({
        url: url,
        params: parameter,
        method: 'get',
        responseType: 'blob',
    })
}

/**
 * 下载文件
 * @param url 文件路径
 * @param fileName 文件名
 * @param parameter
 * @returns {*}
 */
export function downloadFile(url, fileName, parameter, type) {
    // console.log(url, fileName, parameter, type, '类型');
    let fileType = '';//下载文件类型,项目需求要excel和word两种格式,有需要的伙伴可以自行搜索下其他格式进行替换即可
    switch (type) {
        case '.doc': fileType = 'application/msword'; break;
        case '.xls': fileType = 'application/vnd.ms-excel'; break;
    }
    return downFile(url, parameter).then((data) => {
        console.log(data);
        if (!data || data.size === 0) {
            Vue.prototype['$message'].warning('文件下载失败')
            return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName)
        } else {
            //核心
            let blob = new Blob([data], { type: fileType })
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
        }
    })
}
//在页面中使用
//下载的点击事件
handleOk_dowload() {
    downloadFile(url, fileName, '', '.xls').then((res) => {
        if (res.success) {
            console.log(res);
         }
    })
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值