Vue force browser to download files with Axios

This tutorial will give you an example of how to force the browser to download the file sent from the server so the users can have it in there local computer. To force the browser to download first your Axios request need to tell the API that you need the buffer response type. Then when you get the raw data you can simply create an object URL from that raw data and programmatically create a link with the append object URL with the file name and extension then click on it and remove the link so it will not keep in the browser after you download it.

Axios

Create a download.js file in the e API folder or any of your preferred API structure folders.

In the ./src/api/download.js

import axios from 'axios';
export function download(path) {
  const { token } = store.state.auth; // if your API required authorization token

  return axios.get(`api-url/${path}`, {
    headers: { Authorization: token }, // if your API required authorization token
    responseType: 'arraybuffer',
  });
}

Reusable force download function

Create a download.js file in the utils folder.

In the ./src/utils/download.js

/**
 * Force browser download
 * @param {Blob} rawData
 * @param {String} filename
 * @param {String} ext
 * @returns
 */
export function forceDownload(rawData, filename, ext) {
  const url = window.URL.createObjectURL(new Blob([rawData]));
  const link = document.createElement('a');
  link.href = url;
  const isHaveExt = filename.endsWith(ext);
  link.setAttribute('download', `${filename}${isHaveExt ? '' : `.${ext}`}`);
  document.body.appendChild(link);
  link.click();
  link.remove();
  return rawData;
}

Usage

In any page or component that you want to download a file from the server, you can import the download, forceDownload function, and use it as the example below. This will trigger the browser the download the raw file data send from the server.

import { download } from '@/api/download'
import { forceDownload } from '@/utils/download'

async downloadFile(item) {
  const { data } = await download(item.path)
  forceDownload(data,’filename’, 'png')
}

Conclusion

To force the browser to download in VueJs there are many ways to do it. In this article there are 3 steps:

  1. Create the API Axios to get raw file data from the server.
  2. Create a reusable function in your preferred folder structure that forces the browser to download from the raw data with the file name and extension.
  3. Use it. Call the API to get the data then force download with the step 2 function.