今天來寫一下如何在Vue的項目中用blob實現點擊下載。
通常window.open可以滿足一般的下載需求坛猪,但是當我們下載時需要帶上請求頭時,window.open就不能滿足該需求皂股,所以這時候就需要用到blob墅茉。話不多說直接上圖。
axios({
url: url, //請求地址
method: "GET", //請求方法
responseType: "blob" //請求類型為blob
}).then(res => {
if (!res) { // 請求失敗
this.$message.error("下載模板文件失敗");
return false;
}
const blob = new Blob([res.data], { // 定義一個blob
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
const downloadElement = document.createElement("a"); // 創(chuàng)建一個標簽
const href = window.URL.createObjectURL(blob); // 創(chuàng)建a標簽的鏈接
downloadElement.style.display = "none";
downloadElement.href = href;
downloadElement.download = "設備信息"; // 下載之后文檔的名字
document.body.appendChild(downloadElement); //把a標簽加入body中
downloadElement.click();
document.removeChild(downloadElement); // 點擊之后移除a標簽
window.URL.revokeObjectURL(href); // 移除url
});