通过百度AI平台申请应用
async getAccessToken() {
const client_id = '填写申请的key';
const client_secret = '填写申请的key';
try {
const {status, data, statusText} = await axios({
url: `/baiduApi/oauth/2.0/token?client_id=${client_id}&client_secret=${client_secret}&grant_type=client_credentials`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
})
if (status !== 200) {
this.$message.error('获取认证信息失败' + statusText);
return;
}
return data.access_token
} catch (error) {
this.$message.error('获取认证信息失败');
return ''
}
},
async idCardIdentify() {
const params = new FormData();
params.append('image', this.baseImg);
params.append('id_card_side', 'front');
const access_token = await this.getAccessToken();
try {
const {status, data, statusText} = await axios({
url: `/baiduApi/rest/2.0/ocr/v1/idcard?access_token=${access_token}`,
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
data: params
});
if (status !== 200) {
this.$message.error('识别信息失败' + statusText);
return;
}
const info = {
'姓名': 'name',
'性别': 'deadGender',
'出生': 'birthDate',
'民族': 'nation',
'公民身份号码': 'idCardNo',
'住址': 'address',
};
return Object.entries(info).reduce((acc, [key, value]) => {
if (key === '出生') {
let date = data.words_result[key].words.replace(/[^0-9]/g, '');
let year = date.slice(0, 4);
let month = date.slice(4, 6);
let day = date.slice(6, 8);
acc[value] = `${year}-${month}-${day}`;
} else {
acc[value] = data.words_result[key].words;
}
return acc;
}, {});
} catch (error) {
this.$message.error('识别信息失败');
return '';
}
}
通过按钮调用返回值
// OCR识别开始。
async takePicturesForIdentification() {
let res = await this.idCardIdentify()
console.log(res)
this.$emit('updateIdCardInfo',res)
this.showDialog = false;
},
返回结果如下
出现跨域问题可通过修改config配置
'/baiduApi': {
target: 'https://aip.baidubce.com', //访问地址
changeOrigin: true,
secure: false, //只有代理https 地址需要次选项
pathRewrite: {
'^/baiduApi': ''
}
}