escape() 经常使用于对js字符串进行编码
encodeURI() 经常使用于对URI跳转进行编码
encodeURIComponent() 经常使用于对参数传递时进行编码(有可能特殊字符,/,=等形成URI的间断问题)
在使用百度ai进行通用文字识别时,发送image=<base64编码>
这种格式时,请求api可能会返回image format error
的问题,颇有多是编码问题致使的,须要使用encodeURIComponent()
这个方法来格式化一下便可,即image=encodeURIComponent(<base64编码>)
html
此例子有跨域问题,须要自行使用后台作一次转发,这里简洁为主,就暂时不考虑了。
简洁为主,只列出了img标签canvas
<img id="my-img" />
// 获取验证码 function getCode64 () { // 寻找该元素 const img = document.querySelector('#my-img') //建立canvas画布 const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height // 画图 const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0, img.width, img.height) // 转换,有前缀,百度api要求去掉前缀 const dataURL = canvas.toDataURL('image/png') // 返回 return dataURL.replace('data:image/png;base64,', '') }
采用了原生的XMLHttpRequest,固然也能够使用fetchapi
实际是有跨域问题,这里暂时不考虑
// 百度通用文字识别api地址,记得加access_token const GeneralURL = 'xxxxx' // 查询验证码 function fetchNum(base64) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() xhr.open('POST', GeneralURL, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') // 此时要进行编码 xhr.send(`image=${encodeURIComponent(base64)}`) xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200 ) { const result = JSON.parse(xhr.responseText) try { const code = result.words_result[0].words resolve(code) } catch (err) { reject(err) } } } }) }
let base64 = getCode64() fetchNum(base64).then(res => { // res为处理结果 })
URL编码转换函数:escape()、encodeURI()、encodeURIComponent()讲解:https://www.cnblogs.com/2f28/p/9748441.html跨域