vue实现图片上传(单张,带缩略图)
效果图:
使用的是elementui
需要先在main.js中引入:
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
前端代码:
<td id="break_text" style="color: #34a0f5;font-weight: bold;width: 100px;">坏卡照片</td>
<td id="break_img">
<!-- 缩略图显示-->
<div class="img-show" v-if="imgUrl">
<img :src="imgUrl" class="avatar">
<span class="actions">
<!-- 放大 -->
<span class="item">
<i class="el-icon-zoom-in" @click="enlarge()"></i>
</span>
<!-- 删除 -->
<span class="item">
<i class="el-icon-delete" @click="del()"></i>
</span>
</span>
</div>
<!-- 坏卡图片上传 -->
<el-upload v-else action="#" class="uploader-avatar"
style="font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;border: 1px dashed #d9d9d9;"
list-type="picture" :auto-upload="false" :show-file-list="false" :on-change="imgPreview">
<i class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<!-- 图片显示对话框 -->
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogUrl" alt="">
</el-dialog>
</td>
data() {
return {
imgUrl: '',
break_base64: '',//坏卡照片(将其转为base64传到后台)
}
}
js代码:
methods: {
//图片缩略图
imgPreview: function (file) {
//生成临时缩略图
this.imgUrl = URL.createObjectURL(file.raw);
//转成base64
const This = this;
const reader = new FileReader();
reader.readAsDataURL(file.raw);
reader.onload = function (e) {
// this.result // 这个就是base64编码了
this.break_base64 = this.result;
//console.log("图片", this.break_base64);
}
},
enlarge: function () {
this.dialogVisible = true;
this.dialogUrl = this.imgUrl;
},
del: function () {
this.imgUrl = '';
this.dialogUrl = '';
},
}
css 代码:
.uploader-avatar >>> .el-upload {
background-color: #fbfdff;
border: 1px dashed #c0ccda;
border-radius: 6px;
box-sizing: border-box;
width: 148px;
height: 148px;
cursor: pointer;
line-height: 146px;
vertical-align: top;
overflow: hidden;
}
.img-show {
position: relative;
border: 1px solid #c0ccda;
border-radius: 6px;
box-sizing: border-box;
width: 148px;
height: 148px;
cursor: pointer;
overflow: hidden;
}
.uploader-avatar >>> .el-upload:hover {
border-color: #409EFF;
}
.uploader-avatar >>> i {
font-size: 28px;
color: #8c939d;
}
.avatar {
width: 148px;
height: 148px;
display: block;
}
.actions {
position: absolute;
width: 100%;
height: 100%;
line-height: 148px;
left: 0;
top: 0;
cursor: default;
text-align: center;
color: #fff;
opacity: 0;
font-size: 20px;
background-color: rgba(0, 0, 0, .5);
transition: opacity .3s;
}
.actions:hover {
opacity: 1;
}
.actions:hover span {
display: inline-block;
}
.actions span {
display: none;
margin: 0 16px;
cursor: pointer;
}