EN
JavaScript - how to download file using axios?
1
answers
3
points
How can I download file using axios?
1 answer
3
points
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 toblob
, /path/to/file.txt
is the path tofile.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 usingclick()
method to start downloading and then removea
element from the body.
0 comments
Add comment