Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 827
Phu Nguyen Avatar asked Dec 16 '10 06:12

Phu Nguyen


1 Answers

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

like image 92
Shadow Wizard Hates Omicron Avatar answered Sep 20 '22 22:09

Shadow Wizard Hates Omicron