首页 > 技术文章 > vue中 单张图片 存为本地Base64 进行上传

zm-97 2020-12-28 14:27 原文

HTML部分
<input @change="uploadPhoto($event)" type="file" class="kyc-passin">
<span style="color: #777A7D">只能上传jpg/png文件,且不超过2MB</span>
<div v-show="formInline">
     <img :src="formInline" alt="" style="width: 100%;height: 100%;margin-top: 20px;">
</div>
按钮想要做的好看,也可在input上绑定一个Id
<input id="uploadbtn" @change="uploadPhoto($event)" type="file" class="kyc-passin">
然后自定义一个按钮,添加点击事件 <button @click="uploadBtn"> <i class="el-icon-upload"></i> 上传 </button>

JS部分
// 点击事件 将按钮绑定 指定Id 的Input
uploadBtn() {
   var fileSelect = document.getElementById("uploadbtn");
   fileSelect.click();
},
  //监听上传
  uploadPhoto (e) {
        // 利用fileReader对象获取file
        var file = e.target.files[0];
        if(file) {
            var filesize = file.size;
            var filename = file.name;
            // 格式判断
            if (!/image\/\w+/.test(file.type)){
                this.$message.error('请上传以jpg、jpeg、png等结尾的图片文件');
                return false
            }
            // 图片大小限制 2,621,440 2M
            if (filesize > 2101440) {
                // 图片大于2MB
                this.$message.error('图片大于2MB');
                return false
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            let that = this;
            reader.onload = (e) => {
                // 读取到的图片base64 数据编码 将此编码字符串传给后台即可
                var imgcode = e.target.result;
                this.formInline = imgcode
            }
        }
        
   },

 

 

推荐阅读