书中自有黄金屋.|

likepoems

园龄:3年1个月粉丝:6关注:0

原生Ajax处理文件流

在通过Ajax处理请求时,可能会遇到需要下载文件的情况,这里简要的说明下处理方法。

let downloadFile = document.getElementById("downloadImportInfo");
let fileUrl = "D:/test.xlsx"; // ajax获取到的文件地址
downloadFile.onclick = function () {
    const xhr = new XMLHttpRequest();
    let url = "localhost:8000/api/downloadUrl/" + fileUrl; //通过接口处理文件
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (this.status == "200") {
            //获取响应文件流  
            let blob = this.response;
            let a = document.createElement('a');
            a.style = 'display:none';
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function (e) {
                a.download = "试验计划信息.xlsx";
                a.href = e.target.result;
                document.body.append(a);
                a.click();
                a.remove();
            }
        }
    }
    xhr.open("get", url, true);
    xhr.send();
}

本文作者:likepoems

本文链接:https://www.cnblogs.com/likepoems/p/16301734.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   likepoems  阅读(163)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起