加载保存文本区域不起作用,如图所示

Load save textarea not working as shown

本文关键字:不起作用 保存 文本 区域 加载      更新时间:2023-09-26

我从这里得到了一些代码,我试图使用它,但是当我尝试它时,它并没有像我预期的那样工作。您能否帮助修复代码,以便出现一个对话框来保存文件,而不是自动下载。它可能只需要对功能进行细微调整......

这是 HTML...

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad">
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>

还有Javascript...

function saveTextAsFile() {
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }
    downloadLink.click();
}
function destroyClickedElement(event) {
    document.body.removeChild(event.target);
}
function loadFileAsText() {
    var fileToLoad = document.getElementById("fileToLoad").files[0];
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

编辑:这个问题是独一无二的,因为我不是在问如何强制下载,而是在问如何打开"另存为"对话框,就像保存图像时出现的对话框一样

编辑:ActiveX可能有答案?

编辑:似乎没有办法用ActiveX做到这一点,但该程序仍然有一个文件名框。为什么程序忽略了这一点?下载的文件名是一个(看起来像(随机生成的数字?

如果你要求获取传统的"另存为..."对话框,则无法通过JavaScript。浏览器根据其默认设置下载文件,这些设置可能直接下载到默认下载位置或可能提供对话框,但这同样基于客户端的设置,而不是 JavaScript。