设置文件路径
创建与启动文件同级的工具集utils,并在其中创建setting.py管理路径。具体内容如下:
import os
# 基础路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# STATIC路径
STATIC_DIR = os.path.join(BASE_DIR,'static')
# TEMPLATES路径
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
# 上传路径
UPLOAD_DIR = os.path.join(os.path.join(STATIC_DIR,'media'),'upload')
模板中的设置
重点:指定form表单的enctype="multipart/form-data"属性,否则文件上传时无法成功。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>我是首页!</p>
<p>{{ current_user.username }}</p>
<img src="/static/media/{{ current_user.icons }}">
<form action="" method="post" enctype="multipart/form-data">
头像:<input type="file" name="icons">
<input type="submit" value="提交">
</form>
</body>
</html>
业务实现
@user_blueprint.route('/index/',methods=['GET','POST'])
@login_required
def index():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
# 获取
icons = request.files.get('icons')
# 保存
file_path = os.path.join(UPLOAD_DIR,icons.filename)
icons.save(file_path)
user = current_user
user.icons = os.path.join('upload',icons.filename)
db.session.add(user)
db.session.commit()
return redirect(url_for('user.index'))