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

Asked

Viewed 789 times

11

I need the user to click a button to download the text that is within of textarea as a JSON file, for example:

User click on button lower -> Start downloading the file textarea.json

An example that expresses better:

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

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

  • Can explain better the relationship between/textarea and JSON?

  • It might be better to include your current code, both involving the textarea and the expected JSON.

  • 1

    "read carefully"... What, the two lines of explanation? I saw the summary on the main page and opened the question waiting for at least 4 paragraphs...

  • 1

    I’m sorry, but it’s really hard to understand I tried to explain to some and they didn’t understand... It is as follows: I already have the code that generates the JSON text that is in the textarea only need to download it as a file . json.

1 answer

10


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

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

Demo

The problem is that the browser will decide the name of the file that will be downloaded. It has a gambit for this, but will only work in browsers that support the attribute download in 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 without compatibility issues, pass the content to the server and force the download from there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.