Element里面有一个 el-upload 组件
https://element.eleme.cn/2.13/#/zh-CN/component/upload
话不多说直接上代码 可能不是最优但能解决问题就是好方法
<template>
<div>
<el-upload action="https://jsonplaceholder.typicode.com/posts/" :limit="2" list-type="picture-card"
:on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="successfile" :on-error="error"
:on-exceed="exceed" accept="image/png,image/jpg,image/jpeg,image/gif">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<img width="50px" height="50px" :src="dialogImageUrl" alt="">
<button @click="get">获取</button>
</div>
</template>
<script>
export default {
name: '',
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
imglist: []
}
},
components: {
},
methods: {
// 删除
handleRemove(file, fileList) {
console.log(file, fileList);
this.imglist = []
for (let i = 0; i < fileList.length; i++) {
this.baseimg(fileList[i].raw)
}
},
// 点击查看
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
// 成功
successfile(response, file, fileList) {
console.log(response, file, fileList)
this.baseimg(file.raw)
},
// 上传失败
error() {
console.log(111111111)
this.$message.error('上传失败');
},
// 上传图片超出
exceed() {
this.$message.error('上传个数上线');
},
get() {
console.log(this.imglist)
},
// 公共转换base64
baseimg(file) {
const reader = new FileReader()
const that = this
reader.readAsDataURL(file)
reader.onload = function () { // 图片转base64完成后返回reader对象
that.imglist.push(reader.result)
}
}
}
}
</script>