這篇文章主要介紹了微信小程序 上傳頭像的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家實(shí)現(xiàn)這樣的功能,需要的朋友可以參考下
微信小程序 上傳頭像的實(shí)例詳解
最近在做微信小程序上傳頭像和上傳照片功能就隨手寫一下代碼:
上傳頭像html:
<view class="edit-list"> <text class="list-name list-first">頭像</text> <view class="edit-righr-bar"> <image class="head-portrait" src="{{avatar}}" bindtap='changeAvatar'></image> </view> </view>
登錄后復(fù)制
js代碼:
// 切換頭像 changeAvatar: function () { var that = this; // var childId = wx.getStorageSync("child_id"); // var token = wx.getStorageSync('token'); wx.chooseImage({ count: 1, // 最多可以選擇的圖片張數(shù),默認(rèn)9 sizeType: ['compressed'], // original 原圖,compressed 壓縮圖,默認(rèn)二者都有 sourceType: ['album', 'camera'], // album 從相冊(cè)選圖,camera 使用相機(jī),默認(rèn)二者都有 success: function (res) { console.log(res.tempFilePaths + "修改頁(yè)面") var avatar = res.tempFilePaths; that.setData({ avatar: avatar, upAvatar:true }) }, fail: function () { // fail }, complete: function () { // complete } }) }, 這是是調(diào)用上傳頭像uploadFile方法 // 上傳頭像 app.uploadimg({ url: 'URL地址', path: avatar, header: { 'Content-Type': 'multipart/form-data', "Authorization": "Bearer " + token }, isShow: false }); 上傳頭像代碼uploadFile做了一個(gè)封裝 代碼放在APP.js里 //多張圖片上傳 uploadimg:function(data){ var that= this, i=data.i ? data.i : 0, success=data.success ? data.success : 0, fail=data.fail ? data.fail : 0; wx.uploadFile({ url: data.url, filePath: data.path[i], name: 'fileData',//這里根據(jù)自己的實(shí)際情況改 header: data.header, formData: { sequence:i+1 }, success: (resp) => { success++; console.log(resp) console.log(i+"成功"); } }, fail: (res) => { fail++; console.log('fail:' + i + "fail:" + fail); }, complete: () => { console.log(i); i++; if (i == data.path.length) { //當(dāng)圖片傳完時(shí),停止調(diào)用 console.log('執(zhí)行完畢'); console.log('成功:' + success + " 失敗:" + fail); } else {//若圖片還沒有傳完,則繼續(xù)調(diào)用函數(shù) console.log(i); data.i = i; data.success = success; data.fail = fail; that.uploadimg(data); } } }); },
登錄后復(fù)制
uploadFile 提交默認(rèn)是post方法,后臺(tái)給的接口的時(shí)候需要后臺(tái)做成post
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)!
相關(guān)推薦:
以上就是關(guān)于微信小程序中上傳頭像的代碼的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注有卡有網(wǎng)。