簡體   English   中英

jQuery / Javascript創建文本文件供用戶下載

[英]jQuery/Javascript create a text file for user download

我的網站上有一個表單,可以根據輸入為用戶創建輸出。 我想用此輸出創建一個文本文件供用戶下載(帶有瀏覽器下載提示,沒有安全問題)。

有沒有一種方法可以使用Javascript / jQuery而不先使用PHP在服務器上創建文件?

我可以使用某種Javascript對象作為虛擬文件,以便用戶下載它(以解決用戶沒有從服務器下載真正的txt文件的問題)嗎?

您可以通過使用Blob瀏覽器支持polyfill )來實現。 通過@UselessCode查看此示例

 (function () { var textFile = null, makeTextFile = function (text) { var data = new Blob([text], {type: 'text/plain'}); // If we are replacing a previously generated file we need to // manually revoke the object URL to avoid memory leaks. if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); return textFile; }; var create = document.getElementById('create'), textbox = document.getElementById('textbox'); create.addEventListener('click', function () { var link = document.getElementById('downloadlink'); link.href = makeTextFile(textbox.value); link.style.display = 'block'; }, false); })(); 
 <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM