程序上传头像的实例详解⼩程序上传头像的实例详解
最近在做⼩程序上传头像和上传照⽚功能就随⼿写⼀下代码:
上传头像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.pFilePaths + "修改页⾯")
var avatar = pFilePaths;
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
如有疑问请留⾔或者到本站社区交流讨论,感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!