带有token的图片vue组件:authImg,使用axios下载图片
# 带有token的图片vue组件:authImg,使用axios下载图片
使用axios下载图片
<template>
<div
v-loading="loading"
class="img-container"
>
<img
v-if="src"
:src="src"
v-bind="$props"
v-on="$listeners"
/>
</div>
</template>
<script>
import axios from 'axios';
import Auth from 'utils/auth';
export default {
name: 'authImg',
props: {
authSrc: {
type: String,
default: ''
}
},
data() {
return {
src: '',
loading: false,
imageBlob: null
};
},
watch: {
authSrc: {
handler(val) {
this.revokeUrl();
this.imageBlob = null;
this.getImg(val);
},
immediate: true
}
},
beforeDestroy() {
this.revokeUrl();
},
methods: {
async getImg(url) {
if (!url) {
return;
}
const instance = axios.create({
headers: {
'jwt-token': Auth.getJwtToken()
},
responseType: 'blob'
});
this.loading = true;
const res = await instance.request({
url,
method: 'get'
}).catch(e => {
console.error(e);
this.src = url;
this.imageBlob = null;
}).finally(() => {
this.loading = false;
});
const contentType = (res.headers['content-type'] && res.headers['content-type'].split(';')[0]) ||
'application/octet-stream';
if (contentType.includes('image')) {
this.imageBlob = res.data;
this.src = URL.createObjectURL(res.data);
} else {
this.imageBlob = null;
this.src = url;
// 错误处理
if (contentType.startsWith('application/json')) {
const rawText = await res.data.text();
const raw = JSON.parse(rawText);
if (raw.code && raw.code !== 0) {
this.$message.error(raw.message);
}
}
}
},
getImageBlob() {
return this.imageBlob;
},
revokeUrl() {
if (this.src.startsWith('blob')) {
URL.revokeObjectURL(this.src);
this.src = '';
}
}
}
};
</script>
<style scoped>
.img-container {
height: 100%;
}
</style>
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
上次更新: 2023/06/01, 12:40:50