Last updated: Mar 7, 2024
Reading time·5 min
axios
on button clickasync/await
syntax to download files with axios
To download files using axios
:
responseType
property to blob
when issuing the axios
GET
request.Here is the HTML for the example.
<!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>
And here is the related JavaScript code.
// 👇️ 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');
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
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.
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.
// 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.
document.body.appendChild(anchorElement); anchorElement.click();
Once the download has been completed, we remove the element from the DOM and free up resources.
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.
const fileURL = 'http://localhost:3000/example-file.pdf'; axiosDownloadFile(fileURL, 'my-file.pdf');
If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions.
axios
on button clickThe 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.
<!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>
And here is the related JavaScript code.
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'); });
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.
When you download a file from a URL, the server sends a Content-Disposition response header that looks similar to the following.
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).
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'); });
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.
// 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.
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.
<!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>
And here is the related JavaScript code.
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'); });
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:
You can learn more about the related topics by checking out the following tutorials: