原生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();
}
posted @ 2022-05-23 16:30  likepoems  阅读(153)  评论(0编辑  收藏  举报