文档:https://flask-ptbr.readthedocs.io/en/latest/patterns/fileuploads.html
我正在按照上述说明保存从我的烧瓶应用程序上传的照片;但是,我在UPLOAD_FOLDER上收到KeyError。
我将UPLOAD_FOLDER路径保存在实例文件夹内的flask.cfg文件中:
# flask.cfg
TOP_LEVEL_DIR = os.path.abspath(os.curdir)
UPLOAD_FOLDER = TOP_LEVEL_DIR + '/project/static/img/'
这是route.py
from flask import render_template, Blueprint, request, redirect, url_for, flash
from project.models import Plants
from .forms import AddPlantForm, EditPlantForm
from project import db, app
from werkzeug.utils import secure_filename
import os
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@plants_blueprint.route('/new', methods=['GET','POST'])
def add_plant():
form = AddPlantForm()
if request.method == 'POST':
if form.validate_on_submit():
if 'plant_photo' not in request.files:
flash('No plant photo added')
return redirect(request.url)
file = request.files['plant_photo']
if file.filename=='':
flash('No plant photo selected ')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
url = os.path.join(app.config['IMAGE_URL'], filename)
else:
filename = ''
url = ''
下面的行中的KeyError
#KeyError: 'UPLOAD_FOLDER'
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))