当前位置:网站首页>uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
2022-07-06 16:43:00 【ChangYan.】
想实现的功能为:从本地选择一张图片作为头像,然后将该图片以base64格式存储在数据库中。
效果如下:
- 这个前端页面使用了插件商城里免费的前辈分享的模板:https://ext.dcloud.net.cn/plugin?id=2027

对于html部分点击获取头像前辈已经完成好,下图中的此部分无需更改。
- 下一步要做的就是将上传的头像转化为base64格式

avatarChoose() {
let that = this;
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths;
pathToBase64(tempFilePaths[0]) //图像转base64工具
.then(base64 => {
console.log(base64);
console.log(typeof(base64));
that.avatar = base64; //将文件转化为base64并显示
that.avatarUpload(base64); //同时将头像上传至数据库进行存储
})
.catch(error => {
console.error(error)
})
}
});
},
这里使用了pathToBase64这个工具,所以需要去插件市场里下载并引入到项目中https://ext.dcloud.net.cn/plugin?id=123

我在此处输出了一下转化结果和结果的类型
可以看到控制台的显示,转化成功,而且base64的类型是String字符串

- 现在已经能将刚刚上传的头像显示出来了,接下来就是将该图片存储在数据库中。
在上段代码的最后一步调用了avatarUpload函数
所以添加代码,将数据传至后端:
avatarUpload(avatar) {
let that = this;
var res = {
"userId": that.userId, //对应于哪个用户上传头像
"avatar": avatar //转化成功的base64
}
uni.request({
url: "http://localhost:8080/user/avatarUpload", //传到后端
data: JSON.stringify(res), //要传输的数据
header: {
token: that.token },
method: "PUT",
success(r) {
console.log(r);
if (r.data.message == "操作成功") {
uni.showToast({
title: "设置成功"
});
} else {
uni.showToast({
title: r.data.message,
icon: "error",
});
}
},
fail() {
uni.showToast({
title: "网络错误",
icon: "error",
});
},
});
},
对于后端,先要配置数据库
在表中添加avatar属性
对于这个avatar属性的类型,我设置的是mediumtext,防止溢出,就是说base64太长了,害怕varchar类性存不下。
(其实我最初想的是既然是String字符串,那就设置成varchar,然后百度了一下说varchar的最大长度可以到65535,所以那里的长度我就写成了65535,结果一回车确定,它就自动变成了mediumtext类型,可以说很智能了…)然后在类中添加avatar属性

最后后端的Java在controller处进行接收

@PreAuthorize(value = "hasAuthority('sys:put')")
@ApiOperation("上传头像" )
@PutMapping("/avatarUpload")
public ResponseResult avatarUpload(@RequestBody @Valid User user) {
int res = userService.updateUserById(user);
Map<String, Integer> map = new HashMap<>();
map.put("影响行数",res);
return new ResponseResult<Map>(200,"操作成功", map);
}
这里因为前端只传了userId和avatar,所以调用updateUserById函数完成头像到数据库的存储。最后可以看到运行结果:
存储成功!
边栏推荐
- MySQL master-slave multi-source replication (3 master and 1 slave) setup and synchronization test
- 微信小程序uploadfile服务器,微信小程序之wx.uploadFile[通俗易懂]
- Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
- DAY FIVE
- [vector retrieval research series] product introduction
- Command line kills window process
- pinia 模块划分
- Hydrogen future industry accelerates | the registration channel of 2022 hydrogen energy specialty special new entrepreneurship competition is opened!
- rancher集成ldap,实现统一账号登录
- 【向量检索研究系列】产品介绍
猜你喜欢

Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)

Interface joint debugging test script optimization v4.0

Racher integrates LDAP to realize unified account login

app通用功能测试用例

2022 latest blind box mall complete open source operation source code / docking visa free payment interface / building tutorial

Designed for decision tree, the National University of Singapore and Tsinghua University jointly proposed a fast and safe federal learning system

【2022全网最细】接口测试一般怎么测?接口测试的流程和步骤

Three application characteristics of immersive projection in offline display

Do you still have to rely on Simba to shout for a new business that is Kwai?

MATLIB reads data from excel table and draws function image
随机推荐
kubernetes部署ldap
Wind chime card issuing network source code latest version - commercially available
DAY TWO
openresty ngx_ Lua subrequest
"Latex" Introduction to latex mathematical formula "suggestions collection"
Geo data mining (III) enrichment analysis of go and KEGG using David database
[CVPR 2022] semi supervised object detection: dense learning based semi supervised object detection
一图看懂对程序员的误解:西方程序员眼中的中国程序员
Typescript incremental compilation
Personal digestion of DDD
Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
沉浸式投影在线下展示中的三大应用特点
How can computers ensure data security in the quantum era? The United States announced four alternative encryption algorithms
1000 words selected - interface test basis
SuperSocket 1.6 创建一个简易的报文长度在头部的Socket服务器
iMeta | 华南农大陈程杰/夏瑞等发布TBtools构造Circos图的简单方法
Use source code compilation to install postgresql13.3 database
Imeta | Chen Chengjie / Xia Rui of South China Agricultural University released a simple method of constructing Circos map by tbtools
GEO数据挖掘(三)使用DAVID数据库进行GO、KEGG富集分析
Use Yum or up2date to install the postgresql13.3 database