【问题标题】:How to create a txt file from a string with exactly whats what is in the string?如何从字符串中创建一个 txt 文件,其中包含字符串中的内容?
【发布时间】:2021-03-04 07:09:47
【问题描述】:

我创建了一个简单的 HTML 文件,它有一个 textarea、两个文本输入和一个按钮,当单击该按钮时,它会下载 textarea 中的内容,并将文本输入中的内容作为名称。这对我来说已经工作了很长时间,直到我用 # 键入文本。当我输入 # 时,它会创建仅包含 # 之前的内容的 txt 文件。这是我如何下载它的代码。

function generate() {
    var textToSave = document.getElementById('Input1').value;
    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
    hiddenElement.target = '_blank';
    hiddenElement.download = document.getElementById('fileName').value+'.' + document.getElementById("fileExtension").value;
    hiddenElement.click();
}

我只能使用 #,所以我需要一种方法让文件保留所有文本。

【问题讨论】:

    标签: javascript html string download txt


    【解决方案1】:

    你应该试试a blob

    var textToSave = document.getElementById('Input1').value;
    
    var hiddenElement = document.createElement('a');
    
    hiddenElement.download = 'string.txt';
    var blob = new Blob([textToSave], {
        type: 'text/plain'
    });
    hiddenElement.href = window.URL.createObjectURL(blob);
    hiddenElement.click();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2020-07-22
      • 2011-03-14
      • 2010-09-24
      相关资源
      最近更新 更多