【问题标题】:Need to save textArea value in file using javascript (.sql file Extension)需要使用 javascript(.sql 文件扩展名)将 textArea 值保存在文件中
【发布时间】:2018-03-19 10:56:26
【问题描述】:

尝试将 textarea 值保存在 sql 文件(.sql 文件扩展名)中,但它不起作用。

如果更改类型:'text\plain 而不是保存在 .txt 文件中,但是 类型:'application\sql' 比不使用 .sql 文件扩展名保存

<html>
<body>

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveSqlAsFile()">Save Text to File</button></td>
    </tr>>
</table>

<script type="text/javascript">

function saveSqlAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"application/sql"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

</script>

</body>
</html>

【问题讨论】:

  • 你为什么首先需要 application/sql?我假设您只是在编写文本数据,因此不需要指定类似的内容,text/plain 应该可以正常工作。

标签: javascript blob mime-types


【解决方案1】:

只需在文件名中添加扩展名:

function saveSqlAsFile() {
    var textToSave = document.getElementById("inputTextToSave").value,
        textToSaveAsBlob = new Blob([textToSave], { type: "application/sql" }),
        textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob),
        fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value,
        downloadLink = document.createElement("a");


    downloadLink.download = fileNameToSaveAs + ".sql";
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2021-08-30
    • 2011-08-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多