在通过Ajax处理请求时,可能会遇到需要下载文件的情况,这里简要的说明下处理方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| let downloadFile = document.getElementById("downloadImportInfo"); let fileUrl = "D:/test.xlsx"; 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(); }
|