您当前的位置: 首页 > 

【03】

暂无认证

  • 6浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

纯js实现url地址文件的下载

【03】 发布时间:2021-02-05 09:24:14 ,浏览量:6

前端进行文件下载

1、通过XMLHttpRequest获取文件流

2、生成a标签,href为文件流,浏览器直接就是下载文件

3、注意:跨域文件不能下载

var outputFile = function (content, filename) {
        var eleLink = document.createElement('a');
        eleLink.download = filename;
        eleLink.style.display = 'none';
        var blob = new Blob([content]);
        eleLink.href = URL.createObjectURL(blob);
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    };
    function urlToBlob(the_url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.open("get", the_url, true);
        xhr.responseType = "blob";
        xhr.onload = function() {
            if (this.status == 200) {
                if (callback) {
                    callback(this.response);
                }
            }
        };
        xhr.send();
    }

    function downloadFile(url){
        urlToBlob(url, (res)=>{
            outputFile(res, url.slice(url.lastIndexOf('/')+1))
        })
    }

demo地址 https://yuan30-1304488464.cos.ap-guangzhou.myqcloud.com/blog/other/%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD.html

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0622s