Categories
JavaScript Answers

How to Download Data From a URL with JavaScript?

Spread the love

We can create an invisible link and click it with JavaScript to download a file.

To do this, we write:

const downloadURI = (uri, name) => {
  const link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
downloadURI('https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc', 'sample.doc')

We have the downloadURI function that takes the uri of the file to download and the name of the file that’s downloaded.

In the function body, we create an a element with the document.createElement method.

Then we set the download attribute with:

link.download = name;

to set the filename of the downloaded file to name .

Next, we set the href attribute with:

link.href = uri;

Then we call appendChild to append the link to the body element.

And then we click on the link by calling click .

And finally, we call removeChild to remove the link from the body.

Now when we run the downloadURI function, files should be downloaded if it can’t be opened by the browser directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *