🚀 个人简介:某大型国企资深软件开发工程师,信息系统项目管理师、CSDN优质创作者、阿里云专家博主,华为云云享专家,分享前端后端相关技术与工作常见问题~
💟 作 者:码喽的自我修养🥰
📝 专 栏:uniApp与微信小程序 🎉🌈 创作不易,如果能帮助到带大家,欢迎 收藏+关注 哦 💕
🌈🌈文章目录
一、template模版
这里主要使用uniapp官方的图片选择器组件----uni-file-picker,特别方便
<!-- 用户头像 -->
<view class="form-input">
<view class="label" style="display: flex; align-items: center;">{{ getText('userProfile') }}</view>
<view class="example-body custom-image-box">
<uni-file-picker v-model="form.profileUrl" :value="form.profileUrl" limit="1" :del-icon="false" disable-preview :imageStyles="imageStyles"
file-mediatype="image" @select="uploadAvatar">选择</uni-file-picker>
</view>
</view>
二、定义数据
data() {
return {
imageStyles: {
width: 64,
height: 64,
border: {
radius: '50%'
}
},
} }
三、上传图片逻辑
// 上传头像
uploadAvatar(e) {
console.log("e:",e);
this.avatarUrl = e.tempFilePaths[0]; // 获取图片的本地路径
// 上传图片
if (this.avatarUrl) {
const token = uni.getStorageSync('token');
uni.uploadFile({
url: getTotalUrl('/api/ybpf/pc/uploadImg'), // 你的服务器上传接口地址
filePath: this.avatarUrl, // 选择的图片路径
name: 'file', // 必填,后台用来解析的文件名
header: {
Authorization: token
},
success: (uploadFileRes) => {
// 上传成功的处理...
console.log("上传成功的处理...", JSON.parse(uploadFileRes.data));
let data = JSON.parse(uploadFileRes.data)
let argumentsObj = {
name: data.data[0].name,
type: "image",
url: data.data[0].url
}
this.form.profileUrl = []
this.form.profileUrl.push(argumentsObj)
console.log("this.form.profile:",this.form.profileUrl);
},
fail: (err) => {
// 上传失败的处理...
console.error("上传失败的处理...",err);
}
});
}
},
四、提交与图片回显
// 提交
async getInfoById(userId) {
try {
const { data } = await request(UPDATE_SUERINFO + userId, { method: 'GET'});
console.log("提交成功返回data:",data);
this.form = data
this.form.roleId = Number( this.form.roleId )
this.form.profile = this.form.profile.split(',')[0].split(';')[1];
//回显设置成数组,不然不回显
let argumentsObj = {
name: '',
type: "image",
url: this.form.profile
}
this.form.profileUrl = []
this.form.profileUrl.push(argumentsObj)
} catch (e) {
console.log('提交出错了:',e);
return false;
}
},
以上是用uni-file-picker官方封装好的组件实现的,其实底层原理是用到了三个uniapp处理文件的API,分别是👇👇👇
uni.chooseImage、 uni.previewImage、uni.uploadFile
奉上官方详细地址,感兴趣的诸君可自行查阅和研究:
https://uniapp.dcloud.io/api/media/image?id=chooseimagehttps://links.jianshu.com/go?to=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Funiapp.dcloud.io%2Fapi%2Fmedia%2Fimage%3Fid%3Dchooseimage
https://uniapp.dcloud.io/api/request/network-file?id=uploadfilehttps://links.jianshu.com/go?to=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Funiapp.dcloud.io%2Fapi%2Frequest%2Fnetwork-file%3Fid%3Duploadfile
到此这篇文章就介绍到这了,更多精彩内容请关注本人以前的文章或继续浏览下面的文章,创作不易,如果能帮助到大家,希望大家点点收藏+关注 ~💕
更多专栏订阅推荐:
✈️ HTML5与CSS3
🖼️ JavaScript基础
⭐️ uniapp与微信小程序
✍️ GIS地图与大数据可视化