Download File Streams with Axios

Download file streams with Axios

download.js

const axios = require('axios').default; // or import axios from 'axios'
const baseUrl = process.env.VUE_APP_BASE_API

/**
* Download file stream
*
* @param uri e.g. /web/article/exportExcel
* @param params e.g. {id: 1}
*/
export function download(uri, params) {
var url = baseUrl + uri
return axios.get(url, {
params:params,
responseType: 'blob',
}).then((response) => {
// response.data: file stream or error message defined by developers such as {"msg":"something went wrong...","code":500}
resolveBlob(response);
}).catch(error => {
// error.response.data: spring framework ResponseEntity object
alert("Fail to download file")
})
}

function resolveBlob(response) {
const headerval = response.headers['content-disposition'];
if (headerval != null) {
let filename = headerval.split(';')[1].split('=')[1].replace('"', '').replace('"', '');
filename = decodeURI(filename);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
link.remove();
} else {
handleKnownException(response);
}
}

function handleKnownException(response) {
var reader = new FileReader();
reader.onload = function() {
if (reader.result != null) {
const responseData = JSON.parse(reader.result);
if (responseData.code == 500) {
alert(responseData.msg);
}
}
}
reader.readAsText(response.data);
}

Notice:

  • responseType: 'blob'
  • filename = decodeURI(filename)

article.vue

<template>
...
</template>

<script>
import { downLoadFile } from '@/utils/download';

export default {
...
methods: {
handleExportExcel() {
this.fullscreenLoading = true;
downLoadFile("/web/article/exportExcel", this.searchParams)
.then(() => {
this.fullscreenLoading = false;
});
}
}
}
</script>