0

I have about 10 .csv and 10 .xlsx files of sale items that are each zipped and and deployed daily at a URL specified by an API get request I make depending on which file the user wants to download.

So basically, when I call the API, I get back a string of the destination URL, and it's hot, so if you navigate to that url, the file downloads for the user, however this is how I'm doing it, and I'm wondering if there is a better way, or an Angular way?

Here is the response I get the URL from the API get request when the user changes a radio button for the file they want:

{
    "fileUrl": "https://example.com.csv.zip"
}

Then I'm using @ngrx store to set that destination URL in state. I won't go into that here...

Here is the method that is called when the user clicks the download button:

downloadCSV() {
    const url = this.state.destinationUrl;
    this.http.get(url).subscribe(res => {

        // Don't like modifying the DOM just to download a file :(
        const link = document.createElement('a');
        link.download = this.state.destinationUrl;
        link.href = this.state.destinationUrl;
        document.body.appendChild(link);

        // Don't like forcing an event :(
        link.click();

    }, (error) => {
        console.log('error fetching file download');
    });
}

The problem is, this seems hacky, and I am looking for a better solution. Is there a better way of doing this, keeping in ind that I want to avoid popup blockers? I have seen file-saver used in Angular but I don't think I can create a Blob out of the .zip file location and us FileSaver.saveAs(blob, 'example.zip'). Any suggestions would be greatly appreciated.

  • 1
    You could open it in a tab, causing it to download, and since it was a file most browsers will just close the tab again – Deckerz Oct 17 '17 at 14:42
  • 1
    Take a look to this answer: https://stackoverflow.com/a/39657478/5119765 It shows how to retrieve a PDF from an url to a blob. So, you'll be able to use `file-saver`. – ADreNaLiNe-DJ Oct 17 '17 at 14:44

1 Answers1

0
download() {
    const url = 'mydomain.com';
    if (url) {
        const link = document.createElement('a');
        link.href =  url;
        document.body.appendChild(link);
        link.click();
    }
}