XMLHttpRequest下载文件


转自:https://blog.csdn.net/Angel_jn/article/details/108059927 (前端 XMLHttpRequest 实现下载excel文件)

       const xhr = new XMLHttpRequest();
            xhr.open('get', 'http://192.168.1.102:3333/');
            xhr.send();
            xhr.responseType = 'blob'; //设置请求回来的数据为blob方式
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 数据在 this.response 保存
                    // excel 的 MIME 格式为 application/vnd.ms-excel
                    var blob = new Blob([this.response], {
                        type: "application/vnd.ms-excel"
                    });
                    // 创建a链接 href链接地址 download为下载下来后文件的名称
                    var aa = document.createElement('a');
                    aa.href = URL.createObjectURL(blob);
                    aa.innerHTML = 'a链接';
                    aa.download = 'aa.xls';
                    aa.style.display = 'none'; //隐藏a标签 直接调用a标签的点击事件
                    document.body.appendChild(aa);
                    aa.click();
                }
            }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM