Reputation: 2016
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
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
Reputation: 2016
The solution can be found here:
JavaScript blob filename without link
The steps are the following:
<a>
tag.href
attribute to the blob's URL.download
attribute to the filename.<a>
tag.Upvotes: 4