配置代理
proxy: {
'/baiduApi': {
target: 'https://aip.baidubce.com', //访问地址
changeOrigin: true,
secure: false, //只有代理https 地址需要次选项
pathRewrite: {
'^/baiduApi': '',
},
},
},
先获取token
//获取百度图片识别的token
this.axios.get('/baiduApi/oauth/2.0/token?grant_type=client_credentials&client_id=KXBwgOkyn6H&client_secret=32uqmGIdHqD7RcrBRkVRG&',{headers:{
dataType:'json'
}}).then(res =>{
if(res.status ==200){
this.access_token = res.data.access_token;
}
})
拿着上面获取的token去上传文件
<el-upload
accept="image/png,image/jpg"
action="contractaches/uoadBatch"
class="upload-demo"
drag
:headers="viewData.myHeaders"
multiple
:on-success="handleAvatarSuccess"
>
<el-icon
class="el-icon-upload"
style="font-size: 40px; margin-top: 40px"
>
<upload-filled />
</el-icon>
<div class="el-upload__text">
将文件放在此处或
<em>点击上传</em>
</div>
<template #tip>
<div class="el-upload__tip">jpg/png 大小小于500kb的文件</div>
</template>
</el-upload>
将图片转成base64再切割上传去识别
const handleAvatarSuccess = (res, file) => {
console.log(res, file)
viewData.imageUrl = URL.createObjectURL(file.raw)
console.log(viewData.imageUrl)
var fileObj = file.raw
var reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = () => {
viewData.fileData = reader.result
viewData.fileData = viewData.fileData.split(',')
viewData.fileData = viewData.fileData[1]
var form = new FormData()
// 文件对象
form.append('image', viewData.fileData)
form.append('access_token', viewData.access_token)
imageExtract(form).then((res) => {
console.log(res)
})
}
}
api接口:
export function imageExtract(data) {
return axiosInstance({
url: `/rest/2.0/ocr/v1/accurate_basic`,
method: 'post',
headers: {
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
},
data,
})
}