微信小程序上传头像功能实现,示例代码
时间: 2023-12-20 20:49:55 浏览: 197
以下是微信小程序上传头像的示例代码:
1. 在wxml文件中添加上传头像的按钮:
```
<view class="avatar-container">
<image class="avatar" src="{{avatarUrl}}"></image>
<button class="upload-btn" bindtap="chooseImage">上传头像</button>
</view>
```
2. 在js文件中定义chooseImage函数,调用wx.chooseImage方法选择图片并上传:
```
Page({
data: {
avatarUrl: '/images/avatar.png'
},
chooseImage: function () {
var that = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
that.setData({
avatarUrl: tempFilePaths[0]
})
wx.uploadFile({
url: 'your upload url',
filePath: tempFilePaths[0],
name: 'avatar',
formData: {
'user': 'test'
},
success: function (res) {
var data = res.data
//do something
}
})
}
})
}
})
```
3. 在app.json文件中添加上传头像所需的权限:
```
{
"pages": [
"pages/index/index"
],
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序定位"
},
"scope.writePhotosAlbum": {
"desc": "你的相册将用于小程序上传头像"
}
}
}
```
阅读全文