Nikhil Das Nomula
1 min readAug 19, 2020

--

Download files in front end — Vue

If you want to download the files as an attachment(this assumes that the backend service that you are calling returns the file blob with content disposition header as true) then you can simply do this

<a href="<service-url>" download="<name-of-the-downloaded-file">File name that you want to show</a>

2. If you want to download the file to the browser then you can do this. Note that if the files are large, I would suggest the above method

<template>  
<a :href="url" @click.prevent="getFileFromServer()">{{ label }}
</a></template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component({})
export default class DownloadFile extends Vue {
@Prop() url!: string;
@Prop() label!: string;
async getFileFromServer(): Promise<void> { const fileName = this.url.substring(this.url.lastIndexOf("/") + 1); const response = await fetch(this.url);
const blob = await response.blob();
const newBlob = new Blob([blob]);
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
} else {
// For other browsers: create a link pointing to the ObjectURL containing the blob.
const objUrl = window.URL.createObjectURL(newBlob);
const link = document.createElement("a");
link.href = objUrl;
link.download = fileName;
link.click();
// For Firefox it is necessary to delay revoking the ObjectURL. setTimeout(() => {
window.URL.revokeObjectURL(objUrl);
}, 250);
}
}
}
</script> <style lang="scss" scoped>
</style>

--

--