需要使用javascript(.sql文件扩展名)将textArea值保存在文件中

时间:2018-03-19 10:56:26

标签: javascript blob mime-types

尝试在sql文件(.sql文件扩展名)中保存textarea值,但它无效。

如果更改类型:' 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>

1 个答案:

答案 0 :(得分: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();
}