To download a file in the browser with Vue.js, we can make a GET request to get the file response data.
Then we can create a link from it and click on it programmatically to download the file.
For instance, we can write:
<template>
<div id="app">
<a
href="#"
@click.prevent="
downloadItem({
url:
'https://test.cors.workers.dev/?https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
label: 'example.pdf',
})
"
>
download
</a>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "App",
methods: {
async downloadItem({ url, label }) {
const response = await axios.get(url, { responseType: "blob" });
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);
},
},
};
</script>
We have the downloadItem
method that takes an object with the file url
to download, and the label
property which has the file name.
In the method, we call axios.get
to get the data from the url
.
We set responseType
to 'blob'
to let us download the data.
Next, we create a Blob
instance with the response.data
which has the file contents.
type
is set to the MIME type of the file.
Next, we use document.createElement
to create the a
element which we click to download the file.
We set its href
to the URL created by URL.createObjectURL
with the blob
.
And then we set the download
property to the label
file name.
Then we call click
to click on the a
element to do the download.
And finally, we call URL.revokeObjectURL
to clear the URL resources.