uniapp修改头像
以下将是 uniapp 借用七牛云修改头像的代码,但是其他也可借鉴,原理相同,局部更改即可。
以下代码用到的地址皆为七牛云的地址,上传图片很方便,会给你返回图片地址,个人用户注册账号后建立一个存储空间,可免费使用30天,后期换成公司的就好了。
注: 七牛云空间地址必须是公开,否则无法显示
(1)html,一个默认图片和一个修改后的图片
<image v-if="avarShow" :src="avar" mode=""></image>
<image v-else src="../../static/user/head.png" mode=""></image>
(2)js
data() {
return {
imgToken: '', // 本地图片上传到七牛云会返回一个图片路径,需要传图片 token
avar: '', // 修改后的图片路径
avarShow: false, // true 时显示修改后的图片
userId: '' // 用户 id,看接口需求
}
},
methods: {
// 修改头像
updateAvar(way) {
const {imgToken,userId} = this
uni.chooseImage({
count: 1, // 头像只上传1张
sourceType: [way], // way是点击时传入的打开方式相机或相册
success: async (chooseImageRes) => {
//获取头像token的接口
const data = await this.$api.api.user.getImgToken();
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({
url: 'https://upload-z2.qiniup.com/', // 上传地址(七牛云)
filePath: tempFilePaths[0],
name: 'file',
formData: {
token: data.data.body, //头像token,参考返回数据
key: chooseImageRes.tempFiles[0].name // 图片名,移动端可能不存在name,可修改为 key: new Date().getTime()+".png" 随机
},
success: (uploadFileRes) => {
// console.log(uploadFileRes);是一个字符串
const data = JSON.parse(uploadFileRes.data)
// 上传头像接口(参数根据自己的来)
this.$api.api.user.updateHead({
"creator": this.$store.state.loginName, //上传者
"headPath": "http://qapxsiqga.bkt.clouddn.com/"+data.key, // 图片最终的路径,http://qapxsiqga.bkt.clouddn.com/是七牛云空间地址
"userId": userId
}).then(res=>{
console.log(res)
this.avar = "http://qapxsiqga.bkt.clouddn.com/"+data.key // 存入修改后的头像
this.avarShow = true // 显示修改后的头像
})
}
});
}
})
}
}
最后记得获取用户信息,将获取到的头像赋值给 avar,这样一进来就是你换过的头像了,但我们大多数情况都需要限制图片大小和格式,其实很简单,在 uni.chooseImage 的成功函数 success 中添加如下代码:
//此处只适配了 app 和小程序,h5 返回的 tempFiles 不一样
// #ifndef H5
const tempFiles = chooseImageRes.tempFiles;
for(var i=0;i<tempFiles.length;i++) {
var size = tempFiles[i].size;
var path = tempFiles[i].path;
var formatImage = path.split(".")[(path.split(".")).length - 1];
console.log("图片格式" + formatImage)
if (formatImage != "png" && formatImage != "jpg" && formatImage != "jpeg") {
return this.$u.toast('只能上传.png、.jpg、.jpep 格式')
}
if (config.IMG_SIZE < size) {
return this.$u.toast('图片大小限制:' + (config.IMG_SIZE / 1000 / 1024) + "MB")
}
}
// #endif
好了,不知道有没有帮到您,仅供参考!
还没有评论,来说两句吧...