How to download Files and Images using Axios [4 Ways]

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. How to download Files and Images using Axios
  2. Download a file using axios on button click
  3. Reading the filename from the response headers
  4. Using the async/await syntax to download files with axios

# How to download Files and Images using Axios

To download files using axios:

  1. Set the responseType property to blob when issuing the axios GET request.
  2. Create a link element and programmatically click it to initiate a download.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
// 👇️ using a CDN to import axios import axios from 'https://cdn.jsdelivr.net/npm/axios@1.3.6/+esm'; function axiosDownloadFile(url, fileName) { return axios({ url, method: 'GET', responseType: 'blob', }) .then(response => { const href = window.URL.createObjectURL(response.data); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = fileName; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); }) .catch(error => { console.log('error: ', error); }); } const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf');

axios download file

The code for this article is available on GitHub

Make sure to update the URL and the name of the file when calling the function.

For example, if your server starts at http://localhost:39693/ instead of http://localhost:3000 and you have a file called example-file.pdf, your file URL like would look as follows:

  • http://localhost:39693/example-file.pdf
You can also specify a path to a local file, e.g. example-file.pdf (assuming the .pdf file is in the same directory as your script).

We passed a configuration object in the call to axios and set the following 3 properties:

  • url - the server URL to which we're making a request.
  • method - the request method to be used when making the request.
  • responseType - the type of data that the server will respond with.

We set the responseType property to blob because we want to download the file that the server responds with.

index.js
axios({ url, method: 'GET', responseType: 'blob', })

The next step is to create a link element that we'll use to download the file that the server responded with.

index.js
// 1) Create a URL that represents the object we want to download const href = window.URL.createObjectURL(response.data); // 2) Create a link element const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = fileName;

We used the createObjectURL method to create a URL that represents the object that we want to download.

We then used the document.createElement method to create a link element and set the href and download attributes on the element.

The download attribute is used to set the name of the downloaded file.

The next 2 steps are to add the link element to the document and simulate a click to initiate the download.

index.js
document.body.appendChild(anchorElement); anchorElement.click();

Once the download has been completed, we remove the element from the DOM and free up resources.

index.js
document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href);

Make sure to specify the correct URL and set the correct filename and extension in the call to the function.

index.js
const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf');
The code for this article is available on GitHub
Note that the HTTP request has to be made to the same origin (domain) or you have to have CORS configured.

If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions.

# Download a file using axios on button click

The previous example downloads a file immediately as the page loads.

Let's look at an example that uses axios to download a file when a button is clicked.

Here is the index.html file.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <button id="btn">Download file</button> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
import axios from 'https://cdn.jsdelivr.net/npm/axios@1.3.6/+esm'; function axiosDownloadFile(url, fileName) { return axios({ url, method: 'GET', responseType: 'blob', }) .then(response => { const href = window.URL.createObjectURL(response.data); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = fileName; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); }) .catch(error => { console.log('error: ', error); }); } const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf'); });

axios download file on button click

The code for this article is available on GitHub

We added a click event listener to the button element.

Every time the button is clicked, the axiosDownloadFile function is called.

If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions.

# Reading the filename from the response headers

When you download a file from a URL, the server sends a Content-Disposition response header that looks similar to the following.

shell
Content-Disposition: attachment; filename="filename.pdf"

If your server is configured correctly and sends the response header, you could retrieve the name of the file from the header's value (filename.pdf in the example).

index.js
import axios from 'https://cdn.jsdelivr.net/npm/axios@1.3.6/+esm'; function axiosDownloadFile(url, defaultFilename) { return axios({ url, method: 'GET', responseType: 'blob', }) .then(response => { const href = window.URL.createObjectURL(response.data); const anchorElement = document.createElement('a'); anchorElement.href = href; // 1) Get the value of content-disposition header const contentDisposition = response.headers['content-disposition']; console.log('contentDisposition: ', contentDisposition); // 2) set the fileName variable to the default value let fileName = defaultFilename; // 3) if the header is set, extract the filename if (contentDisposition) { const fileNameMatch = contentDisposition.match(/filename="(.+)"/); console.log('fileNameMatch', fileNameMatch); if (fileNameMatch.length === 2) { fileName = fileNameMatch[1]; } } anchorElement.download = fileName; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); }) .catch(error => { console.log('error: ', error); }); } const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf'); });
The code for this article is available on GitHub

We access the headers object on the response to get the value of the content-disposition header.

The fileName variable is initially set a default value.

This is useful because your server might not set the content-disposition header in which case your download will have a random UUID filename.

index.js
// 1) Get the value of content-disposition header const contentDisposition = response.headers['content-disposition']; console.log('contentDisposition: ', contentDisposition); // 2) set the fileName variable to the default value let fileName = defaultFilename; // 3) if the header is set, extract the filename if (contentDisposition) { const fileNameMatch = contentDisposition.match(/filename="(.+)"/); console.log('fileNameMatch', fileNameMatch); if (fileNameMatch.length === 2) { fileName = fileNameMatch[1]; } }

If the Content-Disposition header is set, we extract the filename and reassign the variable.

# Using the async/await syntax to download files with axios

The previous examples used the .then() syntax when downloading files with axios.

However, the async/await syntax is a bit more readable and concise.

Here is the HTML for the next example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <button id="btn">Download file</button> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
import axios from 'https://cdn.jsdelivr.net/npm/axios@1.3.6/+esm'; async function axiosDownloadFile(url, fileName) { try { const response = await axios({ url, method: 'GET', responseType: 'blob', }); const href = window.URL.createObjectURL(response.data); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = fileName; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); } catch (error) { console.log(error); } } const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf'); });

download file with axios using async await

The code for this article is available on GitHub

The code sample downloads a file using axios with the async/await syntax.

If an error occurs in the try block, it gets passed to the catch() block.

I've also written articles on:

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.