Iñigo
Iñigo

Reputation: 2016

Angular - Save blob in local text file?

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!

Upvotes: 3

Views: 13021

Answers (2)

hanan
hanan

Reputation: 1880

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();

Upvotes: 4

Iñigo
Iñigo

Reputation: 2016

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.

Upvotes: 4

Related Questions