Javascript: a SIMPLE way to save a text file?
Asked Answered
A

4

13

I would like to offer to the user the opportunity to save his/her results, as displayed on the web page.

Using the browser's "save as" is no good, it saves the html code, or part of it, instead of saving what is displayed on the page. Even when the option is set to "save as text". There are local links etc.

Using localStorage would be worse. Imagine telling the user that his results are somewhere in a hidden directory and that he/she would need to decode sqlite files...

The examples I found online :

A) are too complicated

B) don't function

C) only show a bit of code and let you guess the rest

Some web sites offer "printer friendly" versions of their page. I could, on the click of a button, open in a new window, or tab, the list of results, in a no frill view. Then the user could "select all" and "copy/paste" to his/her favorite text editor. And save it.

I would like to do better. I would like to have a "Save results" button that would open the usual dialog box "where would you like to save this?" and offer, for instance, the choice between .txt and .rtf formats.

Some stuff I've read seem to hint that this would be illegal. If you could save as .exe, I would understand the security risk. But saving as .txt?

Acidfast answered 28/11, 2020 at 14:31 Comment(3)
Does this answer your question? How to create a file in memory for user to download, but not through server?Confabulation
<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a> : This says would you like to open the file <complicated name> which is of type application/octet-stream (18 bytes)Acidfast
Try <a download="file.txt" href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>. See developer.mozilla.org/en-US/docs/Web/HTML/Element/a#downloadConfabulation
K
15

You can do it this way:
<a href="#" id="download">Download</a>

<script>
var fileName = "myfile.txt";
var fileContent = "Page content...";
var myFile = new Blob([fileContent], {type: 'text/plain'});

window.URL = window.URL || window.webkitURL;
var dlBtn = document.getElementById("download");

dlBtn.setAttribute("href", window.URL.createObjectURL(myFile));
dlBtn.setAttribute("download", fileName);
</script>

This will ask the user to save a file called "myfile.txt" where they'd like to. The contents of the file is up to you.

Khalid answered 28/11, 2020 at 14:42 Comment(0)
F
5

I liked CPlusPatch's solution; unfortunately, I kept experiencing intermittent security failures with it, all of which referenced Blob.

I found a very similar solution here which doesn't use Blob, and I haven't encountered any security issues with it.

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

This download function creates a (hidden) dummy tag in the document, sets its 'href' attr to the file contents you want downloaded, simulates a click on the added tag (triggering a download of the contents), then removes the tag from the body of the document.

Flexion answered 19/9, 2022 at 15:9 Comment(2)
Is appending a to body before calling click necessary?Scheel
It's been a while since I Looked at this code. After testing old code, it seems to work fine when I take out document.body.appendChild of the a (and removeChild as well), however, my setup/site was not complex. I'm not well-versed enough in js or HTML to understand why the original author suggested appending it; see this about creating an element without appending it. #55244774 Maybe this would be relevant if you're dealing with multiple documents (I was not)? Wish someone with more HTML experience would chime in.Flexion
D
1

const link = document.querySelector('a');
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent('insert your text here'));

link.setAttribute('download', 'res.txt');
<a>File</a>

Here, we use the HTML 5 download attribute and encode a URI component of text

Dyarchy answered 28/11, 2020 at 15:14 Comment(0)
B
-2

You could reuse javacript windows print functionality onclick="window.print();" or write your own

Bernoulli answered 28/11, 2020 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.