When using Axios for file downloads, it is essential to set the appropriate response type and process the returned data to facilitate the download. Here is a step-by-step guide on using Axios for file downloads:
-
Configure the Axios request to handle Blob data: To download a file, receive data as a
blob. When sending the request, set Axios'sresponseTypeto'blob'. -
Send a GET request: The GET request sent to the file's location retrieves the file content.
-
Process the response and create a download link: Once the response is received, use the
URL.createObjectURL()method to generate a URL pointing to the blob. -
Trigger the file download: Create an
<a>tag, set itshrefto the previously created blob URL, and set thedownloadattribute to specify the filename. Then, programmatically trigger theclickevent to initiate the download. -
Cleanup: After the download is complete, revoke the object URL to free browser resources.
Here is a specific code example:
javascriptimport axios from 'axios'; function downloadFile(url, filename) { axios({ url: url, // file URL method: 'GET', responseType: 'blob', // critical }).then((response) => { // create a link element const link = document.createElement('a'); // create the download link link.href = window.URL.createObjectURL(new Blob([response.data])); // set the filename for download link.setAttribute('download', filename); // hide the element link.style.visibility = 'hidden'; // append the link to the DOM document.body.appendChild(link); // trigger click link.click(); // remove the link element document.body.removeChild(link); // revoke the URL object window.URL.revokeObjectURL(link.href); }).catch((error) => console.error('File download failed:', error)); } // call the function to download the file downloadFile('https://example.com/somefile.pdf', 'myFile.pdf');
In this example, the downloadFile function accepts the file URL and desired filename as parameters. It uses Axios to send a GET request with responseType set to blob. Upon receiving the response, it creates an invisible <a> tag to trigger the download. Finally, it ensures the blob URL is revoked after completion.