使用Javascript生成和下載文件狈孔?如果考慮到這一點,這并不像您想的那樣安全惧磺,如果沒有用戶交互,就不應該允許這樣做(但是現在允許)捻撑。假設您使用了GoogleChrome磨隘,并且啟用了“自動打開下載的文件”選項,而由于運氣不好顾患,您輸入一個惡意網站并生成一個未知文件的下載番捂。你知道這個故事的結局。然而江解,在最新的瀏覽器中设预,不知道或很少下載的文件擴展名會被阻止,如果您真的想打開該文件(在Chrome中是較少的)犁河,則會出現一個提示鳖枕。因此,文件的自動下載在最近幾年一直難以實現呼股,但是現在隨著HTML 5的引入耕魄,這個任務變得更加容易實現。在這篇文章中彭谁,我們將向您展示一些使用純Javascript直接生成和下載文件的技巧吸奴。
Self-implemented download function(自己實現下載函數)
下面的簡單函數允許您直接在瀏覽器中生成文件,而無需接觸任何服務器缠局。它適用于所有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 :)");
即可
下載屬性指定當用戶單擊超鏈接時將下載目標。只有在設置href屬性時才使用此屬性狭园。
Using a library(使用庫)
創(chuàng)建庫读处,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);
下表顯示了FileSaver.js在不同瀏覽器中的兼容性:
Browser | Constructs as | Filenames | Max Blob Size | Dependencies |
---|---|---|---|---|
Firefox 20+ | Blob | Yes | 800 MiB | None |
Firefox < 20 | data: URI | No | n/a | Blob.js |
Chrome | Blob | Yes | [500 MiB][3] | None |
Chrome for Android | Blob | Yes | [500 MiB][3] | None |
Edge | Blob | Yes | ? | None |
IE 10+ | Blob | Yes | 600 MiB | None |
Opera 15+ | Blob | Yes | 500 MiB | None |
Opera < 15 | data: URI | No | n/a | Blob.js |
Safari 6.1+* | Blob | No | ? | None |
Safari < 6 | data: URI | No | n/a | Blob.js |
Safari 10.1+ | Blob | Yes | n/a | None |
注意: 盡管它支持最新的瀏覽器,但您需要了解幾個技巧才能更好運用冤留。
IE < 10
It is possible to save text files in IE < 10 without Flash-based polyfills.
See ChenWenBrian and koffsyrup's saveTextAs()
for more details.
Safari 6.1+
Blobs may be opened instead of saved sometimes—you may have to direct your Safari users to manually
press <kbd>?</kbd>+<kbd>S</kbd> to save the file after it is opened. Using the application/octet-stream
MIME type to force downloads can cause issues in Safari.
iOS
saveAs must be run within a user interaction event such as onTouchDown or onClick; setTimeout will prevent saveAs from triggering. Due to restrictions in iOS saveAs opens in a new window instead of downloading, if you want this fixed please tell Apple how this bug is affecting you.
下面三個就不翻譯了碧囊,一來不影響使用树灶,二來我沒有看里面內容:blush::blush::blush:
本文為英文翻譯過來,原文鏈接:如何在瀏覽器中使用JavaScript創(chuàng)建下載文件