vue2+element-ui 实现文件上传和回显
一、上传<el-form-item label="上传图片"><el-uploadref="upload"action:file-list="device.photo":limit="2"...
·
一、上传
<el-form-item label="上传图片">
<el-upload
ref="upload"
action
:file-list="device.photo"
:limit="2"
list-type="picture"
:auto-upload="false"
:on-change="getFile"
:on-remove="removePhoto"
>
<el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
<span slot="tip" class="el-upload__tip"> 只能上传jpg/png文件,且不超过500KB</span>
</el-upload>
</el-form-item>
js文件只粘贴了部分代码,因为后台要base64,所以有个图片转base64函数。
data() {
return {
device: new Device(),
// 图片对象列表
photos: [],
// 图片base64列表
photoBase64: []
};
},
methods: {
checkPhotoSize() {
let that = this;
let flag = true;
for (let i = 0; i < that.photos.length; i++) {
let size = Math.floor(that.photos[i].size / 1024);
if (size > 500) {
flag = false;
}
}
return flag;
},
// 将file转base64
getBase64(file) {
return new Promise(function(resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function() {
imgResult = reader.result;
};
reader.onerror = function(error) {
reject(error);
};
reader.onloadend = function() {
resolve(imgResult);
};
});
},
getFile(file, fileList) {
this.photos = fileList;
},
removePhoto(file, fileList) {
this.photos = fileList;
},
二、回显
<el-form-item label="上传图片">
<el-upload
ref="upload"
action
:file-list="photoList"
:limit="2"
list-type="picture"
:auto-upload="false"
:on-change="getFile"
:on-remove="removePhoto"
>
<el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
<span slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500KB</span>
</el-upload>
</el-form-item>
回显的时候把后台传给你的base64编码数组放到file-list中即可,同时可以给这个图片命名。以下只粘贴部分js代码
class Photo {
constructor(name, url) {
this.name = name;
this.url = url;
}
}
export default {
data() {
return {
// 照片回显用
photoList: [],
// 图片对象列表
photos: [],
// 图片base64列表
photoBase64: []
};
},
components: {
Title,
Header
},
mounted() {
var device = this.$route.params.device;
let photoList = [];
for (var index = 0; index < device.photos.length; index++) {
photoList.push(new Photo("图片" + (index + 1), device.photos[index]));
}
this.photoList = photoList;
}
}
三、运行结果
上传:
回显(只是例子,没有用上面的图片):
更多推荐
已为社区贡献1条内容
所有评论(0)