js根据路径下载文件

1.利用iframe下载

let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.setRequestHeader('Authorization', `Bearer ${accessToken}`)
xhr.onreadystatechange = handler
xhr.send()

function handler () {
    if (this.readyState === this.DONE) {
        if (this.status === 200) {
            let iframe = document.createElement('iframe')
            iframe.style.display = 'none'
            iframe.id = 'g-exportProgram-iframe'
            iframe.src = URL.createObjectURL(this.response)
            document.body.appendChild(iframe)
        } else {
            console.error('下载失败')
        }
    }
}

2.利用a标签下载并且修改文件名

function getBlob(url, cb) {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.setRequestHeader('Authorization', `Bearer ${accessToken}`)
    xhr.onload = function() {
        if (xhr.status === 200) {
            cb(xhr.response);
        }
    };
    xhr.send();
}

function saveAs(blob, filename) {
    //ie10的msSaveBlob 和 msSaveOrOpenBlob 方法允许用户在客户端上保存文件
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        let link = document.createElement("a");
        let body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
    }
}

function download(url, filename) {
    getBlob(url, function(blob) {
        saveAs(blob, filename);
    });
}

download(url,fileName)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值