微信小程序上傳頭像


最近在做微信小程序上傳頭像和上傳照片功能就隨手寫一下代碼:

 

上傳頭像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>
 
js代碼:
// 切換頭像
changeAvatar: function () {
var that = this;
// var childId = wx.getStorageSync("child_id");
// var token = wx.getStorageSync('token');
wx.chooseImage({
count: 1, // 最多可以選擇的圖片張數,默認9
sizeType: ['compressed'], // original 原圖,compressed 壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // album 從相冊選圖,camera 使用相機,默認二者都有
success: function (res) {
console.log(res.tempFilePaths + "修改頁面")
var avatar = res.tempFilePaths;
that.setData({
avatar: avatar,
upAvatar:true
})
 
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
這是是調用上傳頭像uploadFile方法
// 上傳頭像
app.uploadimg({
url: 'URL地址',
path: avatar,
header: {
'Content-Type': 'multipart/form-data',
"Authorization": "Bearer " + token
},
isShow: false
});
 
上傳頭像代碼uploadFile做了一個封裝 代碼放在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',//這里根據自己的實際情況改
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) { //當圖片傳完時,停止調用
console.log('執行完畢');
console.log('成功:' + success + " 失敗:" + fail);
 
} else {//若圖片還沒有傳完,則繼續調用函數
console.log(i);
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);
}

}
});
},
 
uploadFile 提交默認是post方法,后台給的接口的時候需要后台做成post


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM