最近在做項目的時候遇到Excel導出功能,后端返回的是文件流,前端如何實現下載功能,以下是項目用的源碼,有需要可直接復制使用。
// 下載 downLoad(id) { this.$axios .get( this.baseUrl + "social/download?id=" +id, {responseType: "blob"} ) .then((res) => { let blob = res.data; let a = document.createElement("a");
//由於后台返回文件名稱是通過response返回的 //因此需要從response headers中content-disposition響應頭中獲取文件名稱fileName,如上圖所示 let headers = res.headers; let fileName = headers["content-disposition"]; fileName = fileName.split('=')[1] //download是a標簽的一個屬性,可以自定義文件名稱 a.download = fileName; a.href = URL.createObjectURL(blob); document.body.appendChild(a); a.click(); document.body.removeChild(a);
}); },