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 using HTML5

download file with HTML5 example

if the image is present on the client side or web server, we can simply use an anchor tag with a download attribute containing the 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 a click event to download the file like an anchor click event

Here is an example code for downloading the 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. You can check other posts on How to always run some code when a promise is resolved or rejected

Download File using JQuery

Conclusion

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