3

I have a plain text variable which I want to store and save on a .txt file using Angular.

So far I have tried the following:

var data = new Blob([text], {type: 'text/plain'});
const url= window.URL.createObjectURL(data);
window.open(url);

Being text the variable with the plain text content. It seems to work but it opens de blob on a new browser tab, and I need it to be downloaded as whatever.txt.

How can I achieve this? Thanks!

Iñigo
  • 1,877
  • 7
  • 25
  • 55
  • 1
    Check this one out https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link – Rahul K Pandey Sep 13 '19 at 11:53
  • 1
    Finally found the solution here: [JavaScript blob filename without link](https://stackoverflow.com/a/19328891/10143290) – Iñigo Sep 16 '19 at 07:47

2 Answers2

4

The solution can be found here:

JavaScript blob filename without link

The steps are the following:

  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.
Iñigo
  • 1,877
  • 7
  • 25
  • 55
3

This is working code from my application

const file = new window.Blob([data], { type: contentType });

const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";

const fileURL = URL.createObjectURL(file);
  downloadAncher.href = fileURL;
  downloadAncher.download = fileName;
  downloadAncher.click();
hanan
  • 1,768
  • 1
  • 14
  • 19