使用饿了吗控件显示本地图片
使用el-upload花了很长时间来处理本地显示图片的问题,下面贴出我的代码(调试通过)给大家参考,本人也是参考别人原生写法,
以下为代码
``
界面部分
请把c-input修改为原控件,我们使用已重新包装
<c-input tabindex="20" label="ctlOrg.logFileName" prop="logFileName" v-model="ctlOrgModel.logFileName"
disabled></c-input>
<el-button-group>
<el-button v-if="logoImgUrl" @click="logoPicPreview">放大</el-button>
<el-button v-if="logoImgUrl" @click="logoPicRemove">清除</el-button>
</el-button-group>
<el-upload
ref="fileUpon"
drag
:auto-upload="false"
name="ctlOrgModel.logFileName"
action=""
list-type="picture-card"
:limit="1"
accept="image/*"
:show-file-list="false"
:on-change="loadLogoFileFromDisk">
<img v-if="logoImgUrl" :src="logoImgUrl" fit="fill" style="width: auto;height: auto" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-card>
</el-form-item>
<el-dialog :title="ctlOrgModel.logFileName" top="10px"
close-on-click-modal
close-on-press-escape
center
:visible.sync="imgPreviewVisible">
<img width="100%" :src="logoImgUrl" alt="">
</el-dialog>
JS
// 成功装载图片
loadLogoFileFromDisk: function(res, fileList) {
const file = fileList[0].raw
const fileSize = file.size
const fileType = file.type
if (!fileSize) {
this.$message('无效的文件,请重新选择!')
this.logoPicRemove()
return
}
if (fileSize / 1024 / 1024 > 2) {
this.$message('上传图片大小不能超过 2MB!')
this.logoPicRemove()
return
}
if (fileType.indexOf('image') === -1) { // 如果不是图片格式
this.$message('不是有效的图片文件,或格式不支持,请重新选择!')
this.logoPicRemove()
return
}
const thisVue = this
this.logoPicRemove()
this.ctlOrgModel.logFileName = file.name
const reader = new FileReader() // 创建读取文件对象
reader.readAsDataURL(file) // 发起异步请求,读取文件
reader.onload = function() { // 文件读取完成后
// 读取完成后,将结果赋值给img的src
// console.log(reader)
thisVue.logoImgUrl = reader.result
}
},
logoPicPreview: function() {
this.imgPreviewVisible = true
},
logoPicRemove: function() {
this.$refs.fileUpon.clearFiles()
this.logoImgUrl = ''
this.ctlOrgModel.logFileName = ''
},
。。。