自己實現下載函數
下面的簡單函數允許您直接在瀏覽器中生成文件,而無需接觸任何服務器。它適用於所有HTML5就緒的瀏覽器,因為它使用了a標簽的下載屬性:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
//調用download("hello.txt","This is the content of my file :)");即可
使用庫
創建庫,FileSaver.js在不支持saveAs()的FileSaver接口的瀏覽器中實現它。如果您需要保存更大的文件,或者BLOB的大小限制,或者沒有足夠的內存,那么請看一看更高級的StreamSaver.js,它可以使用新的StreamsAPI的強大功能將數據直接異步保存到硬盤中。同時支持進度查看,取消和何時完成。
下面的代碼段允許您生成一個文件(具有任何擴展名)並下載它,而無需鏈接任何服務器:
var content = "What's up , hello world";
// any kind of extension (.txt,.cpp,.cs,.bat)
var filename = "hello.txt";
var blob = new Blob([content], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);