首先關於前端下載肯定會想到a鏈接,但是我在使用的時候發現a標簽會打開這個網址而不是下載文件,所以我發現了一個好的方法,感覺不錯,來分享一下
話不多說,上代碼
// 下載文件 _downLoad(url, fileName) { const url2 = url.replace(/\\/g, "/"); const xhr = new XMLHttpRequest(); xhr.open("GET", url2, true); xhr.responseType = "blob"; //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA=='); // 為了避免大文件影響用戶體驗,建議加loading xhr.onload = () => { if (xhr.status === 200) { // 獲取文件blob數據並保存 saveAs(xhr.response, fileName); } }; xhr.send(); },
url表示文件的路徑,fileName表示下載文件名