UploadItem.vue
3.08 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<template>
<el-upload
class="avatar-uploader"
:action="uploadUrl"
:http-request="uploadSumit"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="currentValue" :src="currentValue" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div class="el-upload__tip" slot="tip" :class="{error:tipsError}">{{tips}}</div>
</el-upload>
</template>
<script>
import { request } from "@/api/fetch-api.js";
/**
* 外层插件可通过监听:v-on:before-upload;v-on:after-upload两个事件监听上传结果
* after-upload(success, src)
*/
export default {
props: ["value"],
data() {
return {
imageUrl: this.value,
uploadUrl: "https://api.k.wxpai.cn/bizproxy/kdapi/file/upload",
tips: "只能上传jpg/png文件,且不超过2MB",
tipsError: false,
uploadInterval: 0
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg" || file.type === "image/png";
const isLt2M = file.size / 1024 < 2000;
if (!isJPG) {
this.tipsError = true;
this.tips = "上传图片只能是 JPG|PNG 格式!";
// this.$message.error("");
}
if (!isLt2M) {
this.tipsError = true;
this.tips = "上传图片大小不能超过 2MB!";
}
return isJPG && isLt2M;
},
uploadSumit(params) {
this.tipsError = false;
this.uploadStart();
this.$emit("before-upload");
let data = {
path: "/pro/tianbao",
file: params.file
};
request
.form(this.uploadUrl, data)
.then(result => {
this.uploadEnd();
this.imageUrl = result.content;
this.$emit("input", this.imageUrl);
this.$emit("after-upload", { success: true, src: this.imageUrl });
})
.catch(res => {
this.uploadEnd();
this.$emit("after-upload", { success: false, src: this.imageUrl });
});
},
uploadStart() {
let that = this;
let times = 0;
this.uploadInterval = setInterval(function() {
times++;
let t = times % 4;
let s = "";
for (let i = 0; i < t; i++) {
s += ".";
}
that.tips = "上传中" + s;
}, 500);
},
uploadEnd() {
clearInterval(this.uploadInterval);
this.tips = "只能上传jpg/png文件,且不超过2MB";
}
},
computed: {
currentValue: function() {
return this.value;
}
}
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
padding: 10px;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 120px;
height: 120px;
line-height: 120px;
text-align: center;
}
.avatar {
max-width: 120px;
max-height: 120px;
display: block;
}
.error {
color: red;
}
</style>