Download file streams with Axios
download.js
const axios = require('axios').default; const baseUrl = process.env.VUE_APP_BASE_API
export function download(uri, params) { var url = baseUrl + uri return axios.get(url, { params:params, responseType: 'blob', }).then((response) => { resolveBlob(response); }).catch(error => { 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>
|