Display the β€œSave As” dialog and save the contents of the selected text inside the text field to a file on the client PC

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

I have a form that shows some information related to the user in a text box. If the user wants to save the information, he will copy the text from the text field, then click the [Save] button, a save dialog will appear, which allows the user to select the appropriate path, then export the selected text to a text file.

The problem is that I don’t know how to display the Save As dialog and write the selected path as a text file on the client site (can it use Javascript or JQuery?). So I wonder if anyone can give me some hint?

Many thanks.

+5
source share
1 answer

IE's 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 specified text field to a file with a name equal to the identifier of the text field.

For other browsers, you can read the following: Does execCommand SaveAs work in Firefox?

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

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

, txt

+13

All Articles