-1

I have this condition where on click of a button , I make a fetch request which will give me a url of a file that needs to be downloaded. How do I achieve the same?

Fetch API will give me a link to a file which needs to be downloaded

Help would be appreciated

<Button
             fluid={false}
              size={"small"}
              onClick={this.download}
>
Download
</Button>


download = async () => {
    try {
           let response = await fetch('/fetch/downloadurl');
           let json = await response.json();
           let url = json.url;
           // Need to write the download code here
           window.open(url); // not working
    } catch (error) {
      console.log(error);
    }
  };

1
  • Can you try adding await before the window.open?
    – Karin C
    Commented Aug 8, 2019 at 10:37

2 Answers 2

2

Try this answer: https://stackoverflow.com/a/54626214/9220122

function download(url, name) {
    var link = document.createElement('a');
    link.download = name;
    link.href = url;
    link.click();
}
0

There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).

  1. Just set your document.location.href to the data URI.
  2. <a href="your-data-uri" download="filename.txt">

Preferably you can use Downloadify javascript library (https://github.com/dcneiner/Downloadify) this works on all browsers

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.