Download text from a textarea as a file without server-side language

10

I need the user to click a button to download the text text as a JSON file, for example:

User clicks the button - > Begins downloading file textarea.json

An example that best expresses:

downloadFile(document.querySelector('textarea').innerHTML);

Where I just need to download the code contained in the first parameter.

    
asked by anonymous 21.04.2014 / 14:45

1 answer

9

There is no ideal way to do this only on the client side. In the browsers that support data URIs , you can do this:

function downloadFile(conteudo) {
    window.location.href = 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(conteudo);
}

Demo

The problem with this is that the browser will decide the name of the file that will be downloaded. There is a clue to this, but it will only work on browsers that support the download attribute on anchors :

function downloadFile(conteudo, filename) {
    var ancora = document.createElement('a');
    ancora.href = 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(conteudo);
    ancora.download = filename;
    ancora.click();
}

Demo

If you want a solution with no compatibility issues, pass the content to the server and force the download from there.

    
22.04.2014 / 03:15