版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woshidamimi0/article/details/86082428
使用组件,然后on-change绑定一个方法来获取文件信息,auto-upload设置为false即可
<el-upload action='' :on-change="getFile" :limit="1" list-type="picture" :auto-upload="false">
<el-button size="small" type="primary">选择图片上传,最多上传一张图片</el-button>
</el-upload>
定义methods方法,当上传文件就会触发绑定的函数,然后文件的内容就会绑定到函数的参数里面,这样用file.raw就可以获取文件的内容了。
getFile(file, fileList) {
console.log(file.raw)
},
然后自定义一个方法,用来把图片内容转为base64格式,imgResult就是base64格式的内容了。转为base64字符串要调用h5特性中的FileReader这个api,但是这个api不能return,所以用promise封装一下。
getBase64(file) {
return new Promise(function(resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function() {
imgResult = reader.result;
};
reader.onerror = function(error) {
reject(error);
};
reader.onloadend = function() {
resolve(imgResult);
};
});
},
最后调用一下
getFile(file, fileList) {
this.getBase64(file.raw).then(res => {
console.log(res)
});
},