Welcome folks today in this blog post we will he downloading images
and files from internet
url using axios
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <title>File Download Example</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <form> <label for="url">Enter URL:</label> <input type="text" id="url" name="url"> <br><br> <button onclick="downloadFile()">Download</button> </form> </body> </html> |
As you can see we have the simple html5
user input field where we allow the user to enter the url
of the file
or image url and then we have the button to download
the file or image. And we are calling the downloadFile()
method to actually start the download operation from url. Now we need to define this method as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<script> function downloadFile() { // Get the value of the input field let url = document.getElementById('url').value; // Use Axios to download the file axios({ url: url, method: 'GET', responseType: 'blob', }).then((response) => { // Create a link element to trigger the download const link = document.createElement('a'); link.href = window.URL.createObjectURL(new Blob([response.data])); link.setAttribute('download', 'downloaded-file'); // set the file name document.body.appendChild(link); link.click(); }).catch((error) => { console.log(error); }); } </script> |
The function gets the value of the input field, uses Axios to download the file from the specified URL, creates a link element, sets its href
to the downloaded file, and triggers the browser’s download feature. The catch()
block will be executed if there is an error while downloading the file