2

What is the recommended way for the following:

An array of entities should be downloaded over a button. The button is called Download transactions and should do exactly that without forcing the user to "right click and 'save site as...'".

I have an entity Transaction and an array containing it.

Entity:

export class Transaction {
  title: string;
  category: string;
  period: string;
  value: string;
}

This was the last try I did to download this array as a file:

  exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    const fileURL = URL.createObjectURL(file);
    location.href = fileURL;
  }

This loads the tab containing the result in the current window, but as plain text and not as downloadable file.

I know that there are a LOT of questions about this topic, none I found worked for me. Any help is appreciated! :)

codepleb
  • 10,086
  • 14
  • 69
  • 111

1 Answers1

4

the following function might be what you are looking for:

function download(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(blob, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

and then

exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    download(file,"fileName.json");
  }
Yuval Perelman
  • 4,499
  • 1
  • 22
  • 32
  • I saw a similar approach somewhere, but why do I need to insert a second "button to click"? I will test this, but is this really how we are supposed to provide such functionality? – codepleb Jun 24 '17 at 14:05
  • A web browser was not designed to save files which are not downloaded from a remote server and were explicitly approved by the end user, and if you think of it it's a potential security threat that such a thing is possible. That's just a simple workaround. – Yuval Perelman Jun 24 '17 at 14:58
  • Ok it works (I wonder how often I'm gonna say that in this new world :D). Thank you friend, this bothered me for way too long. – codepleb Jun 25 '17 at 07:40