鍍金池/ 問答/人工智能  HTML/ 在輸入框輸入文本 可下載成文本文件 怎么實(shí)現(xiàn)

在輸入框輸入文本 可下載成文本文件 怎么實(shí)現(xiàn)

輸入框內(nèi)輸入的文件 輸入完后 怎么壓入到一個(gè)txt或文本文件里 進(jìn)行下載

回答
編輯回答
落殤

思路:獲取input的輸入內(nèi)容,然后調(diào)用下面的函數(shù),把內(nèi)容作為文本下載

關(guān)鍵代碼:

    // fileName 是文件名,可以自定義,如 abc.txt
    // content 是input輸入的內(nèi)容
    createAndDownloadFile=function(fileName, content) {
        const aTag = document.createElement('a');
        const blob = new Blob([content]);
        aTag.download = fileName;
        aTag.href = URL.createObjectURL(blob);
        aTag.click();
        URL.revokeObjectURL(aTag.href);
    }
2018年7月24日 06:58
編輯回答
默念

直接把下載按鈕的href屬性寫成data:text/plain,<文本內(nèi)容>,可以使用JavaScript修改具體的文本內(nèi)容

2017年11月14日 14:30
編輯回答
大濕胸

補(bǔ)充一樓,講的很明白啊

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>保存文本文件到本地</title>
</head>
<body>
  <input type="text" id="inputVal" value="qqq">
  <div id="save">保存</div>
</body>
<script type="text/javascript">
    createAndDownloadFile=function(fileName, content) {
        const aTag = document.createElement('a');
        const blob = new Blob([content]);
        aTag.download = fileName;
        aTag.href = URL.createObjectURL(blob);
        aTag.click();
        URL.revokeObjectURL(aTag.href);
    }
    var save=document.getElementById("save");
    save.addEventListener("click",function(){
        createAndDownloadFile("txt文件",document.getElementById("inputVal").value);
    });
</script>
</html>

2017年3月6日 19:23
編輯回答
背叛者

var a = document.createElement('a')
var content = 'download text';//文件內(nèi)容
var blob = new Blob([content])
a.textContent = 'Click here to Download'
a.href = URL.createObjectURL(blob)
a.download = '下載.txt'
document.body.append(a)
2017年1月17日 06:22