我先说这是我对Flask的新手(这是我的第一个项目)并且我有兴趣将它一起黑客攻击,而不是最佳实践。
我目前的代码无法在图片目录中创建用户指定的文件夹。我已经尝试在这里寻找一些答案,但无济于事,我可以让所有这三件事情和谐共处。这是有问题的功能。
@app.route('/', methods = ["GET","POST"])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
foo = request.form.get('name')
if not os.path.exists("/pictures/directory"): os.makedirs("/pictures"+foo)
app.config["UPLOAD_FOLDER"] = "/pictures" + foo
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
return render_template("upload.html")
return render_template("index.html")
如果有人有兴趣看看为什么upload.html首先呈现(这是预期的),但是"继续"按钮无法呈现index.html,我非常感激。
如果有人对其余部分感到好奇,请点击这里:https://bitbucket.org/dillon9/ss
编辑1:感谢你们两位,我有一个半功能的前端和一个功能齐全的后端。新代码被推送。希望我能接受你的两个答案
答案 0 :(得分:2)
这是因为您的foo
变量不能保存用户提供的值。您首先获得用户使用
foo = request.form.get('name')
但是在使用之前你会立即为同一个变量分配其他东西
foo = "/directory/"
编辑:现在您的目录可能是在C:\或其他东西中创建的。将您的代码更改为此类
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
foo = request.form['name']
path = os.path.dirname(os.path.abspath(__file__)) + "/pictures/"+foo
if not os.path.exists(path):
os.makedirs(path)
app.config["UPLOAD_FOLDER"] = path
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
return render_template("upload.html")
return render_template("index.html")
答案 1 :(得分:2)
您的代码中有一些要改变的地方。
<强>首先强>
通常,根页面"/"
被映射到index
命名函数。
@app.route('/', methods = ["GET","POST"])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
foo = request.form.get('name')
if not os.path.exists("/pictures/directory"):
os.makedirs("/pictures"+foo)
app.config["UPLOAD_FOLDER"] = "/pictures" + foo
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
return render_template("upload.html")
return render_template("index.html")
<强>第二强>
使用单个按钮(在本例中为Update
)更有意义 - 更新内容和重定向,然后您可以放弃Continue
按钮。
<强>第三强>
在 upload.html 文件中,您必须更正表单代码
<form action="" method=post enctype=multipart/form-data>
到
<form action="{{ url_for("index") }}" method= "post" enctype= "multipart/form-data">
所以你将action
属性作为值赋予处理此表单的函数的url。最后,在值周围添加双引号。