开发者

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

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

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

The 开发者_Python百科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?

Thank you very much.


IE only solution:

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:

<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.

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

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

NOTE: 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜