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


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;
    			}
    		}
    	}
发布了33 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_22188085/article/details/90484413