用户头像上传
需求分析
- 用户可以进行头像的修改,上传完毕之后更新个人中心跟头像相关的标签内容
- 上传的头像文件保存本地文件
- 用户上传文件,保存到静态资源存储云服务器(拓展)
模板渲染
在 forum/api/account.py
中添加视图函数,返回静态页面
python
@index_bp.get('/account/re_avatar.html')
def re_avatar_view():
return render_template('account/re_avatar.html')
然后再编写前端页面
html
{% extends 'account/index.html' %}
{% block right_container %}
<h3>修改头像</h3>
<form class="layui-form" action="" style="width: 500px;">
<div class="layui-form-item">
<label class="layui-form-label">当前头像</label>
<div class="layui-input-block">
<img src="/static/images/user_pic.png" alt="用户图片" class="user_pic">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"></label>
<div class="layui-input-block">
<button type="button" class="layui-btn" id="ID-upload-demo-btn">
<i class="layui-icon layui-icon-upload"></i> 上传头像
</button>
<div style="width: 132px;">
<div class="layui-upload-list">
<img class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;">
<div id="ID-upload-demo-text"></div>
</div>
<div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
<div class="layui-progress-bar" lay-percent=""></div>
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">头像地址</label>
<div class="layui-input-block">
<input type="text" name="avatar_url" lay-verify="required" placeholder="请输入" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"></label>
<div class="layui-input-block">
<button class="layui-btn layui-btn-sm" lay-submit lay-filter="re-avatar">提交</button>
<button class="layui-btn layui-btn-primary layui-btn-sm" type="reset">重置</button>
</div>
</div>
</form>
{% endblock %}
上传图片
前端实现头像上传
先上传图片,将图片上传成功的地址写入表单。修改头像就只要修改头像的地址就可以了
html
{% block footer_script %}
<script>
layui.use(function () {
let upload = layui.upload;
let layer = layui.layer;
let element = layui.element;
let $ = layui.$;
// 单图片上传
let uploadInst = upload.render({
elem: '#ID-upload-demo-btn',
url: '/api/v1/upload/avatar', // 实际使用时改成您自己的上传接口即可。
before: function (obj) {
// 预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#ID-upload-demo-img').attr('src', result); // 图片链接(base64)
});
element.progress('filter-demo', '0%'); // 进度条复位
layer.msg('上传中', {icon: 16, time: 0});
},
done: function (res) {
// 若上传失败
if (res.code > 0) {
return layer.msg('上传失败');
}
console.log(res)
// $('.user_pic').attr('src', res.url)
$('[name="avatar_url"]').val(res.url)
$('#ID-upload-demo-text').html(''); // 置空上传失败的状态
},
error: function () {
// 演示失败状态,并实现重传
let demoText = $('#ID-upload-demo-text');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
},
// 进度条
progress: function (n, elem, e) {
element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
if (n == 100) {
layer.msg('上传完毕', {icon: 1});
}
}
});
});
</script>
{% endblock %}
后端完成图片上传
修改完毕需要更新父窗口中的内容
python
@index_api.post('/upload/avatar')
def upload_avatar_api():
# 1. 读取图片文件
avatar: FileStorage = request.files.get('file')
filename = avatar.filename
content = avatar.read()
url_name = hashlib.md5(content).hexdigest() + '.' + filename.split('.')[-1]
with open('./static/avatar/' + url_name, mode='wb') as f:
f.write(content)
return {'code': 0, 'msg': '上传图片成功', 'url': '/static/avatar/' + url_name}
修改头像
前端提交修改
javascript
let user_data = JSON.parse(localStorage.getItem('user_data'))
$('.user_pic').attr('src', user_data.avatar_url)
form.on('submit(re-avatar)', function (data) {
let field = data.field
$.ajax({
url: '/api/v1/re-avatar',
type: 'post',
contentType: "application/json",
data: JSON.stringify(field),
success: function (res) {
console.log(res)
if (res.code === -1) {
layui.layer.msg(res.msg, {icon: 2})
} else {
layui.layer.msg(res.msg, {icon: 1})
localStorage.setItem('user_data', JSON.stringify(res.data))
}
}
})
return false
})
后端完成头像修改
python
@index_api.post('/re-avatar')
@jwt_required()
def reload_avatar_api():
current_user.avatar_url = request.get_json().get('avatar_url', None)
current_user.save()
return {'code': 0, 'msg': '修改头像成功', 'data': current_user.as_json()}