
How to download the data from URL using Javascript
Key Takeaways
This guide details programmatic file downloading in JavaScript using the fetch API for remote assets, Blob conversion for local variables, and the native HTML5 download attribute. These methods allow developers to bypass default browser behaviors and ensure resources are saved locally rather than opened in a new tab.
- Utilize the
fetchAPI combined withURL.createObjectURLto programmatically trigger browser downloads for remote resources. - Handle base64 or raw data by wrapping it in a
Blobwith theapplication/octet-streamMIME type to ensure correct file handling. - Leverage the HTML5
downloadattribute on anchor tags for a declarative, low-overhead approach to force-downloading assets.
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>




