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:
xxxxxxxxxx
1
const handleClick = () => {
2
axios.get('/path/to/file.txt', { responseType: 'blob' })
3
.then((response) => {
4
const url = URL.createObjectURL(response.data);
5
const a = document.createElement('a');
6
a.style = 'display: none';
7
a.href = url;
8
a.download = 'file.txt';
9
document.body.appendChild(a);
10
a.click();
11
document.body.removeChild(a);
12
URL.revokeObjectURL(url);
13
})
14
.catch((error) => {
15
console.error(error);
16
});
17
};
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 commentsShow commentsAdd comment