Vue/HTML/JS how to download a file to browser using the download tag
I'm using Laravel and Vue. With https://github.com/maatwebsite/Laravel-Excel
In Laravel route
In the controller method for download, I return https://docs.laravel-excel.com/3.1/exports/exportables.html -> responsible instance
Route::get('users/download', 'userController@download')
->name('users.download');
In my Vue:
<!--
- Page Header Template
-->
<template>
<div class="page-header">
<button
v-if="$is_admin"
class="button secondary download" @click="download">Download
</button>
</div>
</template>
<script>
export default {
methods: {
download () {
const url = '/users/download';
window.location.href = url;
}
},
};
</script>
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.