東營本地網(wǎng)站制作公司品牌策劃與推廣方案
js下載文件方式有使用a標簽的,也有直接用window.open的,還有用form表單的;這里采用的是a標簽的下載方式,一種是url直接下載,另一種是文件的blob數(shù)據(jù)類型進行下載。
文件blob數(shù)據(jù)類型的獲取一般是后端返回文件的二進制流,前端通過請求工具獲取為blob數(shù)據(jù)類型進行下載;也可以這直接通過ajax或fetch等將url轉化為blob數(shù)據(jù)類型,一些特殊的附件直接通過url下載,瀏覽器可能會將其打開,如:pdf。
話不多說直接上代碼:
一、url直接下載文件
/*** 文件url直接下載* @param {String} path 下載鏈接* @param {*} fileName 下載文件名稱, 無文件名默認取url后面名稱*/
const downloadUrl = (path, fileName) => {if(!path) return;const a = document.createElement("a");a.setAttribute("href", path);a.setAttribute("download", fileName);a.setAttribute("target", "_blank");const clickEvent = document.createEvent("MouseEvents");clickEvent.initEvent("click", true, true);a.dispatchEvent(clickEvent);
};
二、文件blob數(shù)據(jù)類型下載文件
/*** 文件blob數(shù)據(jù)格式進行下載* @description 文件下載* @param {String} blob 文件blob數(shù)據(jù)* @param {String} fileName 下載文件名*/
const downloadBlobUrl = function (blob, fileName = "") {if (!blob) return;if ("download" in document.createElement("a")) {// 非IE下載let link = document.createElement("a");if (window.URL) {link.href = window.URL.createObjectURL(blob);} else {link.href = window.webkitURL.createObjectURL(blob);}link.download = fileName;document.body.appendChild(link);link.click();link.remove();} else {// IE10+下載navigator.msSaveBlob(blob, fileName);}
};
需要的上方自取,有疑問或者其他問題歡迎評論溝通,也可加wx溝通賬號與用戶名一致