How to use Fetch API In Javascript

Using the Fetch API, an image is fetched asynchronously. The response, typically containing the image data, is converted into a Blob object. This Blob is transformed into a temporary URL. A dynamic anchor element is created with the URL and desired file name. The anchor is then clicked programmatically to start the download and removed for cleanup.

Example: To demonstrate creating a “Download Image” button. Clicking it fetches an image from a specified URL via a CORS proxy using JavaScript. The response is converted to a Blob object and downloaded as img.jpg.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <title>Download Image</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }

        #downloadBtn {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        #downloadBtn:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <button id="downloadBtn">Download Image</button>

    <script>
        document
            .getElementById('downloadBtn')
            .addEventListener('click', function () 
            {
                const proxyUrl = 
                    'https://cors-anywhere.herokuapp.com/'
                const targetUrl =
'https://media.w3wiki.org/wp-content/uploads/20240426035114/79dd11a9452a92a1accceec38a45e16a.jpg'

                fetch(proxyUrl + targetUrl)
                    .then((response) => 
                    {
                        console.log('Response:', response)
                        return response.blob()
                    })
                    .then((blob) =>
                    {
                        console.log('Blob:', blob)
                        const url = URL
                        
                        .createObjectURL(blob)

                        const link = document
                        .createElement('a')
                        link
                        .href = url
                        link
                        .download = 'img.jpg'
                         // The name for the downloaded file
                        document
                        .body
                        .appendChild(link)
                        link
                        .click()
                        document
                        .body
                        .removeChild(link)

                        URL.revokeObjectURL(url)
                    })
                    .catch(console.error)
            })
    </script>
</body>

</html>

Output:



How to Download Image on Button Click in JavaScript?

Downloading an image on a button click in JavaScript involves creating a mechanism to trigger the download action when a user clicks a button.

Below are the approaches to download image on button click in JavaScript:

Table of Content

  • Using Anchor Tag with Download Attribute
  • Using Fetch API

Similar Reads

Using Anchor Tag with Download Attribute

The “download” attribute in an anchor tag enables direct file downloads from a specified URL when clicked, bypassing the browser’s default behaviour of opening the file. It specifies the filename for the downloaded file, simplifying the download process for users and improving overall user experience....

Using Fetch API

Using the Fetch API, an image is fetched asynchronously. The response, typically containing the image data, is converted into a Blob object. This Blob is transformed into a temporary URL. A dynamic anchor element is created with the URL and desired file name. The anchor is then clicked programmatically to start the download and removed for cleanup....