How to use a custom javascript function with Axios Library In Javascript

Utilize a custom JavaScript function integrated with the Axios library to make asynchronous HTTP requests, facilitating efficient handling of data from external APIs. Axios simplifies AJAX calls, providing promise-based approach for handling responses in web applications.

Example: In this example, we will see the implementation of the above approach with an example.

html




<!DOCTYPE html>
<!DOCTYPE html>
<html>
 
<head>
    <title>Download Images using Axios</title>
    <style>
        .scroll {
            height: 1000px;
            background-color: white;
        }
    </style>
</head>
 
<body>
    <p id="dest">
    <h1 style="color: green">
        w3wiki
    </h1>
    </p>
    <button onclick="download()">
        Download Image
    </button>
    <p class="scroll">
        By clicking the download button
        will generate a random image.
    </p>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">
</script>
<script>
    function download() {
        axios({
            url: 'https://source.unsplash.com/random/500x500',
            method: 'GET',
            responseType: 'blob'
        })
            .then((response) => {
                const url = window.URL
                    .createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'image.jpg');
                document.body.appendChild(link);
                link.click();
            })
    }
 
</script>
 
</html>
 
</html>


Output: 

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



How to trigger a file download when clicking an HTML button or JavaScript?

In today’s digital age, numerous applications offer the feature to upload and download files. For instance, plagiarism checker tools enable users to upload a document file containing text. The tool then checks for plagiarism and generates a report, which can be downloaded by the user.

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.

Table of Content

  • Using Download attribute
  • Using a custom javascript function
  • Using a custom javascript function with Axios Library

Similar Reads

Using Download attribute

The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used....

Using a custom javascript function

...

Using a custom javascript function with Axios Library

First create a textarea to capture user input, where the text content is intended for the downloadable file Now :...