共计 2112 个字符,预计需要花费 6 分钟才能阅读完成。
一、上传文件存储目录
在静态目录下创建名为 upload 的目录作为上传文件存储目录
二、原生文件上传
-
配置
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1] in DefaultConfig.ALLOWED_EXTENSIONS # 原生文件上传 # 上传路径 UPLOAD_FOLDER = os.path.join(BASE_DIR, "static/media") # 配置上传文件的最大尺寸,默认不受限制 MAX_CONTENT_LENGTH = 1024 * 1024 * 2 # 设置允许上传文件的类型 ALLOWED_EXTENSIONS = ["jpg","png","jpeg","gif"] # 验证是否允许上传,允许返回 True,否则返回 False IS_ALLOWED_FUNC = allowed_file
-
上传界面
upfile.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> 上传文件 </title> </head> <body> <form action="/upfile/" method="post" enctype="multipart/form-data"> <input type="file" name="file"><br/> <input type="submit" value="上传"> </form> </body> </html>
-
request.files
ImmutableMultiDict([('file', <FileStorage: 'a.txt' ('text/plain')>)])
-
视图
# 原生文件上传视图 @main.route('/upload/', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') else: # 获取上传文件对象 file = request.files.get('file') filename = file.filename # 获取文件名称 if not current_app.config['IS_ALLOWED_FUNC'](filename): return '该文件类型不允许上传' filePath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename) file.save(filePath) return '文件上传成功'
三、使用 flask-uploads 三方插件
-
安装
pip install flask-uploads
-
创建
from flask_uploads import UploadSet from flask_uploads import TEXT, IMAGES # 与配置文件要对应 限制上传类型 uploads = UploadSet("UPLOADS", extensions=IMAGES) from .ext_uploads import uploads
-
加载
from exts import uploads from flask_uploads import configure_uploads from flask_uploads import patch_request_class # 加载上传三方对象 configure_uploads(app, uploads) # 配置上传文件的大小,默认 64M,如果 size 设置为 None,会读取 MAX_CONTENT_LENGTH 配置的值 patch_request_class(app, size=None)
-
配置
# 上传文件 UPLOADED_UPLOADS_DEST = os.path.join(BASE_DIR, "static/media") MAX_CONTENT_LENGTH = 2 * 1024 * 1024 # UPLOADED_UPLOADS_URL = "http://127.0.0.1:5000:8000/static/media/"
-
示例
from exts import uploads from flask_uploads import UploadNotAllowed @myApp.route("/upfile/", methods=["GET", "POST"]) def upfile(): if request.method == "GET": return render_template("upfile.html") else: file = request.files.get('file') # 获取保存文件的 url img_url = uploads.url(file.filename) print(img_url) try: uploads.save(file, name=file.filename) except UploadNotAllowed as e: pass return "上传文件成功"
正文完
星哥玩云-微信公众号