admin管理员组

文章数量:1279090

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 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!

Share Improve this question edited Sep 10, 2020 at 6:44 Iñigo asked Sep 13, 2019 at 11:32 IñigoIñigo 2,01610 gold badges31 silver badges60 bronze badges 2
  • 1 Check this one out stackoverflow./questions/19327749/… – Rahul K Pandey Commented Sep 13, 2019 at 11:53
  • 1 Finally found the solution here: JavaScript blob filename without link – Iñigo Commented Sep 16, 2019 at 7:47
Add a ment  | 

2 Answers 2

Reset to default 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.

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

本文标签: javascriptAngularSave blob in local text fileStack Overflow