前言
在这里简单记录一下uniapp实现身份证上传功能,简单的描述一下设计的原理,通过uni.chooseImage()获取文件地址,切换本地路径显示对应身份证图片,后通过将file文件转base64上传百度识别,后通过接口获取信息。具体逻辑还是比较简单的
注意:使用百度的识别接口,需要先注册百度账号,获取对应的client_id和client_secret,通知还需要使用获取百度token的接口,在页面中调用一次,将获取到的token携带识别接口进行识别
以下为代码
<template>
<view>
<view class="idCard-box">
<view class="positive">
<image :src="upLoadPositiveImg == ''?positiveImg:upLoadPositiveImg" @tap.prevent="uploadPositive">
</image>
</view>
<view class="reverse">
<image :src="upLoadReverseImg == ''?reverseImg:upLoadReverseImg" @tap.prevent="uploadReverse">
</image>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 正面身份证
// positiveImg: '',//自己图片路径
upLoadPositiveImg: '',
// 反面身份证
reverseImg: '', //自己图片路径
upLoadReverseImg: '',
baidu_token:' ',//百度token
}
},
onLoad() {
this.getACSS_TOKEN()
},
methods: {
// file文件转base64
getImageBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64 = reader.result;
resolve(base64);
}
reader.onerror = error => reject(error);
});
},
// 身份证正面上传
uploadPositive() {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
this.upLoadPositiveImg = res.tempFilePaths[0]
this.getImageBase64(res.tempFiles[0]).then(res => {
this.uploadIdentify(res)
})
}
})
},
// 身份证反面上传
uploadReverse() {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
this.upLoadPositiveImg = res.tempFilePaths[0]
this.getImageBase64(res.tempFiles[0]).then(res => {
this.uploadIdentify(res)
})
}
})
},
// 获取百度token
getACSS_TOKEN() {
let that = this
uni.request({
// url: '/baiduApi/oauth/2.0/token',
url: 'https://aip.baidubce.com/oauth/2.0/token',
method: 'POST',
data: {
grant_type: 'client_credentials',
client_id: '你的',
client_secret: '你的',
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: res => {
this.baidu_token = res.data.access_token
}
});
},
// 上传识别
uploadIdentify(res) {
uni.request({
url: '/baiduApi/rest/2.0/ocr/v1/idcard?access_token=' + this.baidu_token,
method: 'POST',
data: {
image: res,
id_card_side: 'back' // 身份证 正反面 front:身份证含照片的一面 back:身份证带国徽的一面
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: res => {
console.log(res.data)
}
})
},
}
}
</script>
<style lang="scss" scoped>
.idCard-box {
margin-top: 100px;
width: 100%;
display: flex;
background-color: #fff;
.positive {
flex: 1;
height: 200rpx;
display: flex;
align-items: center;
justify-content: center;
image {
width: 80%;
height: 100%;
}
}
.reverse {
flex: 1;
height: 200rpx;
display: flex;
align-items: center;
justify-content: center;
image {
width: 80%;
height: 100%;
}
}
}
</style>
本文是在onload生命周期中调用获取token,具体使用过程中的一些流程需要根据自身情况修改,如有问题希望指点一二