Sometimes, we want to download files from responses made with GET requests.
In this article, we’ll look at how to download files from responses made with GET requests.
Force Download with GET Request using Axios
We can make the response always download by passing our response data into the Blob
constructor.
For instance, we can write:
axios
.get(`download-pdf`, {
responseType: 'arraybuffer'
})
.then(response => {
const blob = new Blob(
[response.data],
{ type: 'application/pdf' }
),
const url = window.URL.createObjectURL(blob);
window.open(url) ;
})
We make a GET request to the download-pdf
endpoint to download our PDF.
We make sure that we specify that the responseType
is 'arraybuffer'
to indicate that it’s a binary file.
Then in the then
callback, we get the response
parameter, which has the data we want in the data
property.
We pass that into the Blob
constructor in an array.
And we specify the MIME type of the response data.
Then we create the URL that lets us download the file with createObjectURL
.
Finally, we call window.open
with the url
to download the file.
We can also specify the file name of the downloaded file by making a small change in the then
callback.
To do that, we write:
axios
.get(`download-pdf`, {
responseType: 'arraybuffer'
})
.then(response => {
const blob = new Blob(
[response.data],
{ type: 'application/pdf' }
),
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "file.pdf";
link.click();
})
Instead of creating an object URL directly, we create an invisible link first and set the file name as the download
property of it.
Then we call click
to download it.
Conclusion
We can make the response always download by passing our response data into the Blob
constructor.