有很多網站會涉及到文件下載,這里我們使用axios 發送請求 接受數據
第一步 模仿jQ 封裝接口
Vue.prototype.$xlsx_post = function (url, data, fun, err) { var userName = getCookie("username") axios({ method: 'post', url: url, responseType: "blob", headers: { 'Authorization': userName ? userName.token_type + userName.access_token : "Basic emh4eTp6aHh5" }, data: data }).then(function (res) { if (fun) { fun(res) } }) .catch(function (error) { if (err) { err(error) } }); }
注意 : responseType 要設置為 blob 告訴服務器你期望的響應格式。
第二步 發送請求 接受數據
this.$xlsx_post( `/rsgl/rstrainperson/exportExcel`, { trainId: this.$route.query.id, userId: this.multipleSelection.join(",") }, res => { const blob = new Blob([res]); // 創建blob對象 const fileName = "培訓管理.xlsx"; const elink = document.createElement("a"); // 創建的標簽 elink.download = fileName; elink.style.display = "none"; elink.href = URL.createObjectURL(blob); // 創建url document.body.appendChild(elink); // 把 創建的標簽追加到body里 elink.click(); URL.revokeObjectURL(elink.href); // 釋放URL 對象 document.body.removeChild(elink); // 移除標簽 this.$message({ message: "導出成功!!!", type: "success" }); this.$refs.multipleTable.clearSelection(); }, err => { this.$message.error("服務器錯誤"); throw err; } );
好了, 希望對大家有所幫助