In some cases, we need to download the data from the URL using Javascript. In this article, I will show you how to download the data from URL using Javascript.
Download the data from URL using Javascript
In my case, I need to download the data from the URL and save it to the local file. I will use the fetch
API to download the data from the URL.
Here is an example code:
const download = async (url, filename) => {
const response = await fetch(url);
const blob = await response.blob();
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
};
download('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 'google.png');
Download base64 data stored in variable
In some cases, we need to download the base64 data stored in the variable. In this case, we need to convert the base64 data to the blob data.
Here is an example code:
const download = (data, filename) => {
const blob = new Blob([data], { type: 'application/octet-stream' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
};
let image = 'data:text/html,HelloWorld!'
download(image, 'hello.html');
Anchor tag download method
In some cases, we need to download the data from the URL using the anchor tag. In this case, we need to create the anchor tag and set the href
attribute to the URL. Then, we need to set the download
attribute to the filename. Finally, we need to click the anchor tag.
Here is an example code:
// Js Methods
const download = (url, filename) => {
const link = document.createElement('a');
link.href=url;
link.download=filename;
link.click();
};
download('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 'google.png');
// Html
<a href="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" download="google.png">Download</a>