Javascript 显示“另存为”对话框并将 textarea 中选定文本的内容保存到客户端 PC 上的文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4458119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:29:11  来源:igfitidea点击:

Display "Save as" dialog and save contents of a selected text inside textarea to a file on client's PC

javascripthtml

提问by Phu Nguyen

Possible Duplicate:
Download textarea contents as a file using only Javascript (no server-side)

可能的重复:
仅使用 Javascript(无服务器端)将 textarea 内容下载为文件

I have a form which shows some user related information in a textarea. If user want to save the information, he/she will copy the text from textarea then click on [Save] button, a save as dialog appear to allow user to choose an appropriate path then export the selected text to text file

我有一个表单,它在 textarea 中显示一些与用户相关的信息。如果用户想保存信息,他/她将从textarea中复制文本然后点击[Save]按钮,出现一个另存为对话框,允许用户选择合适的路径,然后将所选文本导出到文本文件

The problem is that i don't know how to display the Save as dialog and write to the selected path as text file at client site (It may use Javascript or Jquery?). So i wonder if someone could give me some hint?

问题是我不知道如何在客户端显示“另存为”对话框并作为文本文件写入所选路径(它可能使用 Javascript 或 Jquery?)。所以我想知道是否有人可以给我一些提示?

Thank you very much.

非常感谢。

回答by Shadow Wizard is Ear For You

IE only solution:

IE唯一解决方案:

function SaveContents(element) {
    if (typeof element == "string")
        element = document.getElementById(element);
    if (element) {
        if (document.execCommand) {
            var oWin = window.open("about:blank", "_blank");
            oWin.document.write(element.value);
            oWin.document.close();
            var success = oWin.document.execCommand('SaveAs', true, element.id)
            oWin.close();
            if (!success)
                alert("Sorry, your browser does not support this feature");
        }
    }
}

Required HTML sample:

所需的 HTML 示例:

<textarea id="myText"></textarea><br />
<button type="button" onclick="SaveContents('myText');">Save</button>

This will save the contents of the given textarea into a file with name equal to the ID of the textarea.

这会将给定 textarea 的内容保存到一个名称等于 textarea 的 ID 的文件中。

As for other browsers, you can read this: Does execCommand SaveAs work in Firefox?

至于其他浏览器,你可以阅读这个:execCommand SaveAs 在 Firefox 中工作吗?

Test case and working example: http://jsfiddle.net/YhdSC/1/(IE only..)

测试用例和工作示例:http: //jsfiddle.net/YhdSC/1/(仅限 IE..)

NOTE: https://support.microsoft.com/en-us/help/281119/internet-explorer-saves-html-content-instead-of-the-active-document

注意:https: //support.microsoft.com/en-us/help/281119/internet-explorer-saves-html-content-instead-of-the-active-document

It may not work for filetypes other than txt

它可能不适用于 txt 以外的文件类型