关于uniapp上传头像功能实现代码如下
关于uniapp上传头像方法的封装可以直接拿来使用
·
ChangeAvatar() {
//从本地相册选择图片或使用相机拍照
uni.chooseImage({
sourceType: ['album', 'camera'],//选择方式相册或者相机
success: (res) => {
console.log('图片', res)
var tempFilePath = res.tempFilePaths;
var filePath = tempFilePath[0];
console.log(filePath);//输出本地头像路径
//调用上传下载api
uni.uploadFile({
url: '后端提供', //这个是你服务上的php用来处理图片上传的路径(可var_dump($_FILE)出来看看)
filePath: filePath,//要上传文件资源的路径。
name: 'image', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
fileType: 'image',//文件类型,image/video/audio
/* 在请求头里边携带的东西
header: {
'content-type': 'multipart/form-data',
token: uni.getStorageSync('token')
},*/
formData: {
//HTTP 请求中其他额外的formdata数据
token: uni.getStorageSync('token')
},
success: (res) => { //成功回调函数
console.log('this', JSON.parse(res.data), res)
let code = JSON.parse(res.data).code
if (code == 200) {
uni.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
})
//成功后2秒跳转到其他页面并刷新目标页面开始
setTimeout(() => {
uni.redirectTo({
url: '要跳转的页面路径',
success: function(e) {
var page = getCurrentPages()
.pop();
console.log('page', page)
if (page == undefined ||
page == null) return;
page.onLoad();
}
})
}, 2000)
//成功后2秒跳转到其他页面并刷新目标页面结束
}
},
fail: (e) => {
console.log(e, 'shangchuanshibai1');
uni.showToast({
title: '上传失败',
icon: 'loading',
duration: 2000
})
}
})
}
});
},
更多推荐
已为社区贡献3条内容
所有评论(0)