發(fā)布于:2021-01-18 15:27:02
0
97
0
長期以來,強制下載腳本一直是Internet可用性的重要組成部分。我可以通過在服務(wù)器端實現(xiàn)此功能的次數(shù)以及直到今天的PHP Force Download帖子的普及程度來證明這一點。隨著網(wǎng)絡(luò)世界在客戶端方面的發(fā)展,我開始尋找一種無需服務(wù)器即可強制下載的方法,然后在Firefox DevTools Debugger中找到了它。
JavaScript
執(zhí)行此操作的功能非常小,并且依賴于URL.createObjectUrl:
function downloadFile(data, fileName, type="text/plain") { // Create an invisible A element const a = document.createElement("a"); a.style.display = "none"; document.body.appendChild(a); // Set the HREF to a Blob representation of the data to be downloaded a.href = window.URL.createObjectURL( new Blob([data], { type }) ); // Use download attribute to set set desired file name a.setAttribute("download", fileName); // Trigger the download by simulating click a.click(); // Cleanup window.URL.revokeObjectURL(a.href); document.body.removeChild(a); }
該函數(shù)將一個<a> 元素注入到主體中,將其URL設(shè)置Blob為目標(biāo)文件的文本內(nèi)容的值,然后單擊該元素以觸發(fā)下載。該元素在處理過程中保持隱藏狀態(tài),并在click()調(diào)用后立即從DOM中刪除。調(diào)用該函數(shù)后,將立即顯示瀏覽器的下載提示。
我期待著更多地了解createObjectURL 和Blob;那兩個才是這項技術(shù)的真正魔力!
向Sneha Jain大喊,以在Firefox DevTools調(diào)試器中實現(xiàn)這項出色的技術(shù)!