How to download files in Vue
Enabling file downloads is a common requirement in Vue applications, from exporting reports to downloading user-generated content. As the creator of CoreUI with over 11 years of Vue development experience since 2014, I’ve implemented file download functionality in numerous production applications. The most effective solution is to create a blob URL and trigger the download programmatically using an anchor element. This approach works for both API-fetched files and client-generated content.
Create a blob URL and trigger download using a temporary anchor element.
<template>
<button @click='downloadFile'>Download File</button>
</template>
<script>
export default {
setup() {
const downloadFile = async () => {
const response = await fetch('/api/download/report.pdf')
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'report.pdf'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
}
return { downloadFile }
}
}
</script>
The file is fetched from the API and converted to a blob. The URL.createObjectURL() method creates a temporary URL for the blob. A hidden anchor element is created with the blob URL as href and the desired filename as the download attribute. Programmatically clicking the link triggers the browser’s download mechanism. Finally, the temporary link and blob URL are cleaned up to prevent memory leaks.
Best Practice Note
This is the same file download pattern we use in CoreUI Vue components for export features. Always call URL.revokeObjectURL() after download to free memory. For large files, consider adding a loading indicator, and for client-side generated content, create the blob directly from your data without an API call.



