与Vue结合,使用weui 的上传图片

1.引入css

 <link rel="stylesheet" type="text/css" href="../css/jquery-weui.min.css">
 <link rel="stylesheet" type="text/css" href="../css/weui.min.css">

2.html

<div class="weui-uploader">
   <div class="weui-uploader__bd">
        <div style="position: relative;">
            <img :src="imgurl" id="image" width="150px" height="150px"
                style="border: 1px solid rgb(238, 238, 238);" v-show="show">
            <span class="close" v-show="show" @click="del">一</span>
        </div>
        <div class="weui-uploader__input-box" v-show="upload">
            <input id="uploaderInput" type="file" accept="image/jpeg,image/jpg,image/png" class="weui-uploader__input"
                @change="iconChange($event)">
        </div>
    </div>
</div>

3.获取图片base64去头部,并上传图片base64数据

methods:{
	iconChange: function ($event) {
	      function getObjectURL(file) {
	                var url = null;
	                if (window.createObjectURL != undefined) {
	                    url = window.createObjectURL(file);
	                } else if (window.URL != undefined) { // mozilla(firefox)  
	                    url = window.URL.createObjectURL(file);
	                } else if (window.webkitURL != undefined) { // webkit or chrome  
	                    url = window.webkitURL.createObjectURL(file);
	                }
	                return url;
	            }
	            var _this = this;
	            var file = $event.target.files[0];
	            console.log(file.name);
	            
	           //用文件名name后缀判断文件类型,用size属性判断文件大小不能超过500k ,前端直接判断的好处,免去服务器的压力。
	           
	           if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name) ) {
	           
	               	return layer.alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
	               	
	           }else if (file.size >  500 * 1024) {
	           
	                 return layer.alert("文件太大!请上传不超过500k的图片"); 
	            }
	            var src = getObjectURL(file);//获取文件信息 	
	
	            app.show = true;
	            app.icon = src;
	
	            //base64
	            var reader = new FileReader();
	            reader.onload = function () {
	                // 通过 reader.result 来访问生成的 base64 DataURL
	                var base64 = reader.result;
	                //打印到控制台,按F12查看
	                console.log(base64);
					//去掉头部		
	                app.icon = base64.replace(/\r|\n/g, '').replace('data:image/jgp;base64,', '').replace('data:image/png;base64,', '').replace('data:image/jpeg;base64,','');
	
	            }
	            reader.readAsDataURL(file);
	    }
 },
 computed: {
   imgurl: function () {
           if (this.url.length > 0) {
               return this.url;
           } else {
               this.show = false;
               return '';
           }
       }
   }

4.获取后端传过来的base64加上头部显示图片

  <img :src="'data:image/jpeg;base64,'+icon" v-show="show" width="100px" height="100px"> 
Logo

前往低代码交流专区

更多推荐