{

Multiple ways to download a file or image in Javascript?


How to download a file or image from a given url in javascript.

In Web applications, You have a feature download link that downloads the images from a given URL.

You have an anchor link like below.

<a href="url">Download File</a>

when the user clicks on the link, it downloads a file from a server url.

There are multiple ways we can do it.

download file with HTML5 example

if image is present in client side or webserver, we can simply use anchor tag with download attribute contains name of the file to be downloaded

<a class="button" href="localhost.com/assets/name.png" download="name.png">Download File</a>

When clicking on the download link, It downloads the name.png into the browser and saves it to the file system.

If the image or file is coming from Server, This will not work, You have to download using client-side javascript

Fetch javascript to download a file

fetch is a native browser feature introduced in the latest browsers. It is used to fetch the files from a remote server by making a network request and returning the response.

  • It returns the response and converts it to blob object byte code.
  • It calls and creates a url with this byte code
  • Create an anchor inline element and update href to this blob byte code
  • You can update the name of the file to download the attribute
  • Add the anchor element to the DOM tree
  • Finally, initiate click event to download the file like anchor click event

Here is an example code for download file from a given url

      fetch(url)
        .then(resp => resp.blob())
        .then(blobobject => {
            const blob = window.URL.createObjectURL(blobobject);
            const anchor = document.createElement('a');
            anchor.style.display = 'none';
            anchor.href = blob;
            anchor.download = "name.png"";
            document.body.appendChild(anchor);
            anchor.click();
            window.URL.revokeObjectURL(blob);
        })
        .catch(() => console.log('An error in downloadin gthe file sorry'));
}

You can also use async and promises to download files asynchronously.

Conclusion

In this short tutorial, You learned different ways to download files or images in javascript and HTML

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.