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