Coding Triumph

Helpful code snippets & tutorials

How to download a file with JavaScript and Axios

Axios is a lightweight JavaScript library that uses AJAX to communicate with the server. For security reasons, JavaScript, thus AJAX, cannot download and save files to the local filesystem. Fortunately, there is a simple workaround to bypass this limitation with the Blob object. This is the script:

const download = async () => {
    const res = await axios.get('/download', {
      // Important: set the response type as blob
      responseType: 'blob'
    });
    /**
     * Use the blob object and a temporary anchor tag to download the file
     */
    const blob = new Blob([res.data], { type: res.data.type });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    // get filename from the response
    const contentDisposition = res.headers['content-disposition'];
    let fileName = 'unknown';
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="(.+)"/);
      if (fileNameMatch.length === 2) fileName = fileNameMatch[1];
    }
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(url);
  }

Note: Keep in mind that using blob as response type, the entire file will be loaded to the memory and processed before the download begins, even if the server is transferring the data as chunks. So it may not be suitable for large files.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments