Languages

JavaScript - how to download file using axios?

3 points
Asked by:
ArcadeParade
666

How can I download file using axios?

1 answer
3 points
Answered by:
ArcadeParade
666

Quick solution:

const handleClick = () => {
    axios.get('/path/to/file.txt', { responseType: 'blob' })
         .then((response) => {
              const url = URL.createObjectURL(response.data);
              const a = document.createElement('a');
              a.style = 'display: none';
              a.href = url;
              a.download = 'file.txt';
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              URL.revokeObjectURL(url);
        })
        .catch((error) => {
            console.error(error);
        });
};

Explanation:

  • You can download file using axios.get() method, and setting the response type to blob,
  • /path/to/file.txt is the path to file.txt to be downloaded from the server,
  • the next step is to create invisible link (a element) that will trigger the download on click event,
  • simulate click on a element using click() method to start downloading and then remove a element from the body.
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join