目录结构图:
配置app
导包及配置
import os
from flask import Flask, flash, request, redirect, url_for,Request,render_template
from werkzeug.utils import secure_filenameUPLOAD_FOLDER = '文件下载的绝对路径'
# 允许的下载类型
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}app = Flask(__name__)
app.config['SECRET_KEY'] = 'some secret words'
# 配置文件上传后的路径
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000
app.config["AVATAR"]= "默认头像"
# 判断文件类型是否合格
def allowed_file(filename):return '.' in filename and \filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():# 为post请求则if request.method == 'POST':# check if the post request has the file part# 多重判断if 'file' not in request.files:flash('No file part')return redirect(url_for('upload_file'))file = request.files['file']if file.filename == '':flash('No selected file')return redirect(request.url)# 文件合格if file and allowed_file(file.filename):filename = secure_filename(file.filename)# 更改默认头像app.config['AVATAR']= filename# 文件保存到下载目录file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))return render_template('index.html',avatar=app.config["AVATAR"])
app.run(debug=True) #开启debug 运行
index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>更改头像</title><style>#all{margin : 0px auto;height:300px;width:250px;}img{height:250px;width:250px;border-radius: 120px;border:solid 1px gray;}h3{text-align:center;}.alert {position: relative;padding: 7px;margin: 7px 0;border: 1px solid transparent;color: #004085;background-color: #cce5ff;border-color: #b8daff;border-radius: 5px;}</style>
</head>
<body><div id="all"><!-- 插入到页面标题上方 -->{% for message in get_flashed_messages() %}<div class="alert">{{ message }}</div>{% endfor %}<img src="../static/{{ avatar }}" alt="" ><h3>更改头像</h3><form method=post enctype=multipart/form-data><input type=file name=file><input type=submit value=Upload></form>
</div></body>
</html>
运行结果
最好是查看官方文档