flask文件上传
上传约束
- 文件路径配置
# 配置图片存储路径
app.config['UPLOAD_FOLDER'] = os.getcwd()
- 文件大小上限限制
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
- 文件格式设置
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
- 安全问题
- Werkzeug提供的secure_filename()函数来检查文件名
- secure_filename仅返回ASCII字符, 非ASCII(比如汉字)会被过滤掉,空格会被替换为下划线,如图片“中 国 人a b.jpeg”
处理前:保存为“中 国 人a b.jpeg”,需使用“/中%20国%20人a%20b.jpeg”访问
处理后:保存为“a_b.jpeg”,使用“/a_b.jpeg”访问
图片访问
@app.route('/upload/<filename>')
def uploaded_file(filename):
return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'], 'static', 'upload'), filename)
代码
# upload.py
from flask import Flask, request, render_template, url_for, redirect, send_from_directory
from werkzeug.utils import secure_filename
import os
# 定义图片格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
# 配置图片存储路径
app.config['UPLOAD_FOLDER'] = os.getcwd()
# 配置图片允许的最大值
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
def allowed_file(filename):
"""
.rsplit('.', 1): 从字符串末尾开始分割,且只分割一次
判断是否是*.*格式,且末尾的*符合定的文件后缀,返回True or False
"""
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
file = request.files['file'] # 必须与<input type="file" name="file">中'file'保持一致
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_path = os.path.join(app.config['UPLOAD_FOLDER'], 'static', 'upload', file.filename) #注意:没有的文件夹一定要先创建,不然会提示没有该路径
file.save(upload_path)
return 'success'
return render_template('upload.html')
@app.route('/upload/<filename>')
def uploaded_file(filename):
return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'], 'static', 'upload'), filename)
if __name__ == '__main__':
app.run(debug=True)
# upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 上传文件 -->
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
flask_uploads插件
后续补充