/* 转化64格式图片 */
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)
}
})
},
/* 使用 */
this.getBase64(file.raw).then((res) => {
console.log(res)
})
element-ui 实战
<el-upload
class="upload-demo"
action=""
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change='handleChange'
:before-remove="beforeRemove"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList"
:auto-upload="false">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
data() {
return {
fileList: [],
form:{
imgs:[]
}
};
},
methods: {
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)
}
})
},
handleChange(file, fileList) {
this.imageUrList = fileList
this.form.imgs = []
this.imageUrList.forEach(e => {
this.getBase64(e.raw).then((res) => {
this.form.imgs.push(res)
})
})
},
handleRemove(file, fileList) {
console.log(file, fileList);
this.imageUrList = fileList
this.form.imgs = []
this.imageUrList.forEach(e => {
this.getBase64(e.raw).then((res) => {
this.form.imgs.push(res)
})
})
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
}
}