Vue/HTML/JS how to download a file to browser using the download tag

You can fetch the file as a blob and provide it the same way, there will be no request that leads into CORS issues.

Template

<a
  :href="item.url"
  v-text="item.label"
  @click.prevent="downloadItem(item)" />

Vue

methods: {
  downloadItem ({ url, label }) {
    Axios.get(url, { responseType: 'blob' })
      .then(response => {
        const blob = new Blob([response.data], { type: 'application/pdf' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = label
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(console.error)
  }
}

Notes: I used Axios for my example but that’s not a requirement, the blob’s mime type is hardwired for the sake of simplicity.

Leave a Comment