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!

2

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

can you share a stackblitz.com example? Having a live example would help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.