vue:点击上传图片,本地预览,并获取图片的基于base64的二进制流

3 篇文章 0 订阅


HTML代码


<el-form-item label="上传学校主图:">
		<input type="file" ref="fileBtn" @change="uploadImg" />
		<img :src="imgSrc" class="img" ref="img" />
</el-form-item>

JS代码


data(){
		return {
			imgInfo: null,
			imgSrc: null
		}
},    
methods: {
    		async uploadImg() {
    			var that = this;
    			const inputFile = await this.$refs.fileBtn.files[0];
    			let res;
    			console.log('选了图片');
    			console.log(inputFile);
    			this.inputFile = inputFile;
    			if (this.inputFile) {
    				let inputFile = this.inputFile;
    				if (inputFile.type !== 'image/jpeg' && inputFile.type !== 'image/png' && inputFile.type !== 'image/gif') {
    					alert('不是有效的图片文件!');
    					return;
    				}
    				this.imgInfo = Object.assign({}, this.imgInfo, {
    					name: inputFile.name,
    					size: inputFile.size,
    					lastModifiedDate: inputFile.lastModifiedDate.toLocaleString()
    				});
    				console.log(this.imgInfo);
    				const reader = new FileReader();
    				res = reader.readAsDataURL(this.inputFile);
    				console.log('我想想要获取流');
    				reader.onloadend = function() {
    					// var strBase64 = reader.result.substring(84);
    					var strBase64 = reader.result.substring(0);
    					console.log(strBase64);
    				};
    				reader.onload = function(e) {
    					console.log(e);
    					that.imgSrc = this.result;   // 注意:这里的this.result中,这个this不是vue实例,而是reader对象,所以之前用that接收vue示例  that.imgSrc   
    				};
    			} else {
    				return;
    			}
    		}
    	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值