记录一次下载pdf/xsml的需求
生活随笔
收集整理的這篇文章主要介紹了
记录一次下载pdf/xsml的需求
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
記錄一次下載pdf/xsml的需求
PC端需要下載pdf/xls文件,但是有可能生成的文件還沒(méi)有存放到OSS服務(wù)器上。所以需要先判斷路徑是否404,成功之后再使用a標(biāo)簽下載。這個(gè)需求在一個(gè)vue項(xiàng)目中,但是使用axios無(wú)法實(shí)現(xiàn)判斷404,因?yàn)闊o(wú)論是否404,axios的then和catch都會(huì)執(zhí)行。
getAjax(scope) {let _this = thisif(!scope.prefixURL || !scope.filePath) {this.$confirm("暫無(wú)賬單,當(dāng)日的賬單將在16:30左右更新", "提示", {showCancelButton: false,confirmButtonText: "確定",type: "warning"})return false}const fullpath = scope.prefixURL + scope.filePath//發(fā)送Ajax的步驟//第一步: 創(chuàng)建XMLHttpRequest對(duì)象var xhr = null;if (window.XMLHttpRequest) {//如果瀏覽器存在這個(gè)對(duì)象 則以這種方式創(chuàng)建xhr = new XMLHttpRequest();} else {//否則 以下面這種方式xhr = new ActiveXObject("Microsoft.XMLHTTP");}//第二步 準(zhǔn)備發(fā)送 調(diào)用opent方法 (有三個(gè)參數(shù)) 拼接數(shù)據(jù)xhr.open("GET", fullpath, true);xhr.setRequestHeader("Content-Type", "application/pdf");xhr.responseType = "blob";//第三步 發(fā)送 調(diào)用send方法xhr.send(null); //get請(qǐng)求 為null//第四步處理請(qǐng)求 綁定事件onreadystatechangexhr.onreadystatechange = function() {// 狀態(tài)為4 表示收到數(shù)據(jù)if (xhr.readyState === 4) {//狀態(tài)碼為 200 表示數(shù)據(jù)完整if (xhr.status === 200) {const blob = xhr.response;const reader = new FileReader();reader.readAsDataURL(blob); // 轉(zhuǎn)換為base64,可以直接放入a的hrefreader.onload = function (e) {// 轉(zhuǎn)換完成,創(chuàng)建一個(gè)a標(biāo)簽用于下載const name=fullpath.substring(fullpath.lastIndexOf("/")+1);const a = document.createElement('a');a.download = name;a.href = e.target.result;document.body.appendChild(a); // 修復(fù)firefox中無(wú)法觸發(fā)clicka.click();document.body.removeChild(a);}} else {_this.$confirm("賬單生成中,請(qǐng)稍后再試...", "提示", {showCancelButton: false,confirmButtonText: "確定",type: "warning"})}}}}總結(jié)
以上是生活随笔為你收集整理的记录一次下载pdf/xsml的需求的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。