Contents

Download file streams with Axios

download.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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":"internal server error","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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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>
Contents