zl程序教程

您现在的位置是:首页 >  其他

当前栏目

原生Ajax处理文件流

文件AJAX 处理 原生
2023-06-13 09:15:30 时间

本文最后更新于 128 天前,其中的信息可能已经有所发展或是发生改变。

在通过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();
}