vue中 單張圖片 存為本地Base64 進行上傳


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
            }
        }
        
   },

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM