開鎖都在什么網(wǎng)站做最有效的推廣學(xué)校的方式
首先保證 改文件資源能夠通過get請(qǐng)求或者 post請(qǐng)求拿到,基于此基礎(chǔ)上我們可以實(shí)現(xiàn)得知下載完成后的回調(diào) 代碼如下
const getFileAndCallback = (url, callback) => {//定義執(zhí)行作用域const that = this;//首先 初始化一個(gè)原生ajax對(duì)象const xhr = new XMLHttpRequest();//建立xhr請(qǐng)求xhr.open("GET", url, true);//定義xhr傳輸格式未blobxhr.responseType = "blob";//xhr回調(diào)函數(shù)xhr.onload = function(){//接口成功響應(yīng)if (this.status === 200){const blob = this.response;//定義fileReader對(duì)象const fileReader = new FileReader();//使用fileReader原生api 讀取xhr 存入fileReader對(duì)象fileReader.readAsDataUrl(blob);//監(jiān)聽fileReader的加載回調(diào)fileReader.onload = async function(e){//兼容ie11的寫法//ie 11對(duì)文件數(shù)據(jù)的存儲(chǔ)轉(zhuǎn)換api是window.navigator.msSaveBlob(this.response, "文件名/fileName") 或者 window.navigator.msSaveOrOpenBlob(this.response, "文件名/ fileName");if (window.navigator.msSaveOrOpenBlob){try {window.navigator.msSaveOrOpenBlob(this.response, ""文件名/fileName"")}catch(e){//日志記錄解析失敗的情況 理論上不會(huì)出現(xiàn)}}else{//ie11意外的文件下載用的是a標(biāo)簽downloadlet a = document.createElement('a');a.download = "文件名/fileName";a.href = e.target.result;a.click();}};//此時(shí)已經(jīng)下載完成 執(zhí)行回調(diào)callback();}}}
//實(shí)現(xiàn)方法如上