项目是基于我的博文:vue + flask 旅游景点数据分析系统 基础上做的,可以参考之前的博客文章。
1 前端修改
主要是修改Profile.vue
<!-- 头像上传 --><el-form-item label="头像"><el-uploadclass=""action="/api/upload_avatar":on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload":show-file-list="false"><el-button size="small" type="primary">上传头像</el-button></el-upload><img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" alt="头像"/></el-form-item>beforeAvatarUpload(file) {const isJPG = file.type === 'image/jpeg';const isPNG = file.type === 'image/png';const isLt2M = file.size / 1024 / 1024 < 2;if (!(isJPG || isPNG)) {this.$message('上传头像图片只能是 JPG 或 PNG 格式!', 'error');}if (!isLt2M) {this.$message('上传头像图片大小不能超过 2MB!', 'error');}return (isJPG || isPNG) && isLt2M;},handleAvatarSuccess(response, file) {// console.log(response.message)// 假设后端返回的头像 URL 在 response.data.urlconsole.log(response.data.url)this.form.avatar = response.data.url;localStorage.setItem('avatar', response.data.url)// 设置头像this.form = {...this.form}},.avatar {width: 100px; /* 自定义宽度 */height: 100px; /* 自定义高度 */object-fit: cover; /* 确保图片覆盖整个方框 */border: 1px solid #ccc; /* 添加边框以显示方框效果 */
}
Layout.vue 我们修改头像之后,希望标题栏上的头像也可以修改:
// avatarUrl: require("@/assets/avatar.png") // 也可以使用 require 语法引入图片avatarUrl: localStorage.getItem('avatar') //获取头像
2 后端修改
新建一个upload文件夹,用于保存图片。
修改config的内容
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
UPLOAD_FOLDER = 'upload'class Config:# scrapy_demo 就是之前旅游爬虫教程中建的数据库,如果不清楚,可以去看之前的教程# 视频:https://www.bilibili.com/video/BV1Vx4y147wQ# 博客:https://blog.csdn.net/roccreed?type=blogSQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:12345678@localhost/scrapy_demo?charset=utf8'SQLALCHEMY_TRACK_MODIFICATIONS = False# 设置上传文件夹UPLOAD_FOLDER = UPLOAD_FOLDER# 允许的文件扩展名ALLOWED_EXTENSIONS = ALLOWED_EXTENSIONS
修改routes.py,增加上传相关内容:
# 上传图片
@main.route('/upload_avatar', methods=['POST'])
def upload_avatar():if 'file' not in request.files:return make_response(code=400, message='没有文件部分')file = request.files['file']if file.filename == '':return make_response(code=400, message='没有选择文件')if file and allowed_file(file.filename):filename = secure_filename(file.filename)file_path = os.path.join(UPLOAD_FOLDER, filename)file.save(file_path)# 返回头像的 URLreturn make_response(code=0, message="上传成功",data=dict(url=f'/api/upload/{filename}'))return make_response(code=400, message='不支持的文件类型')# 查看图片
@main.route('/upload/<filename>/', methods=['GET'])
def uploaded_file(filename):current_directory = os.getcwd()uoload_path = current_directory + '/' + UPLOAD_FOLDER# print(uoload_path)return send_from_directory(uoload_path, filename, as_attachment=False)
同时用户的更新接口需要增加更新字段avatar:
# 更新用户接口
@main.route('/user/<int:id>', methods=['PUT'])
def update_user(id):data = request.json # 获取JSON数据user = User.query.get(id) # 根据ID查找if not user:return make_response(code=1, message='用户不存在')# 更新字段for field in ['realname', 'job', 'addr', 'intro', 'phone', 'email', 'age','avatar']:if field in data:setattr(user, field, data[field])
3 测试一下
测试一下,已经上传到服务端了。
右上角的头像不会变,但是我们可以刷新一下就可以了,刷新一下,重新读取localStorage,就更新到了。
原因是我们的头像更新(localStorage中,这个实际上是文件了)vue是不会监听的。