iview的Upload图片上传
张渊 Lv2

iview的upload上传组件,项目中经常会遇到上传图片的需求,还需要控制图片进行预览、大小限制、手动控制上传等操作,下面代码是直接通过iview中的upload组件来进行处理图片的自动、手动上传,以及本地图片预览方式。

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
<template>
<Upload
ref="upload"
name="qmfile"
:show-upload-list="false"
:on-success="handleSuccess"
:format="['jpg','jpeg','png']"
:max-size="2048"
:on-format-error="handleFormatError"
:on-exceeded-size="handleMaxSize"
:before-upload="handleBeforeUpload"
type="drag"
action="/activity/uploadIcon"
>
<div style="display: flex;align-items: center;justify-content: center;height: 100%;" v-if="!formParams.currentImgUrl">
<Icon type="md-add" size="40" color="#ffffff"></Icon>
</div>
<img v-if="formParams.currentImgUrl" : src="formParams.currentImgUrl" alt="" class="show-img" >
</Upload>
</template>

<script>
export default{
data(){
return{
formParams: {
currentImgUrl: '',//当前展示图片(也可以直接使用uploadList)
file: {},//文件流
uploadList: [],//图片列表
},

}
},
methods: {
handleSuccess (res, file) {
//上传成功返回处理
if(res.code == 10000){
this.formParams.currentImgUrl = res.img_path;
this.formParams.uploadList[0] = res.img_path;
}else{
this.$Message.destroy();
this.$Message.error(res.msg);
}
},
handleFormatError (file) {
this.$Message.destroy();
this.$Message.warning({
content: file.name + '的文件格式不正确,请选择jpg或png'
});
},
handleMaxSize (file) {
this.$Message.destroy();
this.$Message.warning({
content: '文件 ' + file.name + ' 太大, 超出 2M.'
});
},
handleBeforeUpload (file) {
//本地预览的两种方式
//1 转换成本地可预览路径 2 转换成Base64进行本地预览
// this.formParams.currentImgUrl = URL.createObjectURL(file);//本地可预览路径
this.formParams.file = {};//清空上次
this.formParams.uploadList = [];//清空上次
this.formParams.file = file;
// 转换Base64
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const _base64 = reader.result;
this.formParams.currentImgUrl = _base64;
this.formParams.uploadList[0] = _base64;
}
//限制图片上传数量
const check = this.formParams.uploadList.length < 1;
if (!check) {
this.$Message.destroy();
this.$Message.warning({
content: '最多上传一张图片'
});
}
return check;//false将不执行上传
//注意:手动上传可在此直接 return false,调用时直接使用:
//this.$refs.upload.post(this.formParams.file);
}
}

}
</script>
 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep
本站由 提供部署服务
总字数 12.9k 访客数 访问量