小程序和fetch使用百度云图片识别 失败:"image format error"、"param image not exist"
小程序使用百度云图片识别——失败
“image format error”
注意!注意!注意!
- 去掉base64字符串前面的图片信息头
data:image/jgp;base64,
, - 不要进行什么
urlencode
编码
当上面注意中的内容你满足一项时就会出现下图的错误:
代码示例(可直接复制使用,记得修改你的access_token)
//选择图片
image_classify: function() {
let that=this;
wx.chooseImage({
success(res) {
that.urlTobase64(res.tempFilePaths[0]);
}
})
},
urlTobase64:function(url) {
wx.request({
url: url,
responseType: 'arraybuffer', //最关键的参数,设置返回的数据格式为arraybuffer
success: res => {
//把arraybuffer转成base64
let base64 = wx.arrayBufferToBase64(res.data);
// console.log(base64)
wx.request({
url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=你自己的access_token',
data:{
image:base64
},
method:'post',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success(res) {
console.log(res)
}
})
}
})
},
代码执行结果:
fetch使用百度云图片识别——失败
“param image not exist”
官方规定Content-Type
格式为application/x-www-form-urlencoded
,body传值时千万要注意!!!需要给body传一个键值对构成的字符串:例如:body:"user=哈哈&name=18"
,以下两种传值方式都会出现"param image not exist"
。
第一种错误传值:
第二种错误传值:
以上两种传值方式执行结果:
“image format error”
-
去掉base64字符串前面的图片信息头
data:image/jgp;base64,
, -
根据官网要求进行
urlencode
编码,使用encodeURIComponent编码,而不是encodeURI
,使用encodeURI
会出现"image format error"
错误。encodeURI
编码代码截图:
encodeURI
编码出现"image format error"
:
代码示例
_Classify() {
let url='https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=你自己的access_token';
let options={
"method": "post",
"Content-Type": "application/x-www-form-urlencoded",
};
//ImagePicker是react-native选取图片的插件
ImagePicker.openPicker({
includeBase64: true
}).then(image => {
let img = encodeURIComponent(image.data);
options.body=`image=${img}`;
fetch(url,options)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
})
}).catch(error => {});
}
代码执行结果:
encodeURI()
和encodeURIComponent()
encodeURI()
和encodeURIComponent()
方法可以对URI
进行编码,以便发送给浏览器。有效的URI
中不能包含某些字符,例如空格等。
encodeURI()
-
使用
encodeURI(URIstring);
-
说明
该方法不会对ASCII
字母和数字进行编码,也不会对这些ASCII
标点符号进行编码:- _ . ! ~ * ' ( )
。该方法的目的是对URI
进行完整的编码,因此对以下在URI
中具有特殊含义的ASCII
标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#
-
测试
console.log(encodeURI("https://aip.baidubce.com")) console.log(encodeURI("https://aip.baidubce.com/rest/2.0/image-classify /v1/plant")) console.log(encodeURI(",/?:@&=+$#"))
encodeURI
编码测试结果:
encodeURIComponent()
-
使用
encodeURIComponent(URIstring);
-
说明
该方法不会对ASCII
字母和数字进行编码,也不会对这些ASCII
标点符号进行编码:- _ . ! ~ * ' ( )
。
其他字符(比如 :;/?:@&=+$,#
这些用于分隔URI
组件的标点符号),都是由一个或多个十六进制的转义序列替换的。 -
测试
console.log(encodeURI("https://aip.baidubce.com")) console.log(encodeURI("https://aip.baidubce.com/rest/2.0/image-classify /v1/plant")) console.log(encodeURI(",/?:@&=+$#"))
encodeURIComponent
编码测试结果: