前幾天偶然看見一個人臉識別的小程序demo,覺得很有趣下載下來想玩玩,結(jié)果只是一個框架而已用不了的,花了點時間完善一下
吐槽一下wx.uploadFile這個接口,真是個大坑,最開始調(diào)用時候,我以為它和同期的wx.downloadFile一樣,只需要填入必須的參數(shù)就可以用,結(jié)果還是要配合后臺php的
首先,upload這個接口的url和request一樣指的是php的路徑,而不是download一樣文件路徑
其次,我在最開始一直沒弄懂這個"name"到底應(yīng)該填什么,上傳功能不好用我一直覺得是"name"的原因,官方對于name給的解釋很迷,這里我就給個結(jié)論,大家不要糾結(jié)這個屬性,直接寫file就好,圖片屬性是能用的
最后,人臉識別功能的功能本身是第三方提供的,比如我用的就是阿里云的人臉識別功能,不到一分錢一張圖片充值一塊錢就可以玩的很嗨
那么,上代碼,我的代碼基本就是網(wǎng)上的demo+自己修改
首先是wxml
<view class="container"> <view class="userinfo"> <image class="userinfo-avatar" mode="aspectFit" src="{{tempFilePaths}}" background-size="cover"></image> <text class="userinfo-tips">{{userInfo.tips}}</text> </view> <view class="usermotto"> <button class="button" type="primary" bindtap="chooseimage">{{motto}}</button> </view></view>然后js代碼
var app = getApp()Page({ data: { motto: '上傳靚照', userInfo: {}, tempFilePaths: '' }, chooseimage: function () { var that = this; wx.chooseImage({ //選擇圖片 count: 1, sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有 sourceType: ['album', 'camera'], success: function (res) { var tempFilePaths = res.tempFilePaths that.setData({ tempFilePaths: tempFilePaths[0] }) wx.uploadFile({ //上傳圖片 url: '', //這里是你php的路徑!! filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'multipart/form-data' }, success: function (res) { console.log("add success", res.data); that.uploadImage(res.data); wx.showToast({ title: "圖片上傳成功", icon: 'success', duration: 700 }) } }) } }) }, //事件處理函數(shù) uploadImage: function(picName) { var that = this wx.showToast({ title: '鑒定中,請稍候', icon: 'loading', duration: 2000}) wx.request({ url: '', //這里是阿里云人臉識別功能php的路徑 data: { type: 0, image_url: picName, }, header: { 'Content-Type': 'application/json' }, // filePath: tempFilePaths[0], name: 'file', success: function(res){ console.log(res.data) wx.hideToast() var data = res.data; var sex = data.gender; const genders = { 'Male': '基佬', 'Female': '小仙女' } if(data.face_num == 0){ that.setData({ userInfo:{ tips:'未檢測到人臉' } }) return } else { if (sex == 0) { that.setData({ userInfo: { tips: data.face_num + '位' + data.age + '歲的' + genders.Female } }) } else { that.setData({ userInfo: { tips: data.face_num + '位' + data.age + '歲的' + genders.Male } }) } return } } }) }, onLoad: function () { console.log('onLoad'); }, onShareAppMessage: function () { }})
新聞熱點
疑難解答