我有一个在 apache 后面运行的 flask 应用程序,在我的 index.html 页面上有一个文件上传按钮和一个提交按钮,如下所示:
<form id="package_form" action="" method="POST">
<div>
<p>Upload Packages:</p>
<p><input id="upload_button" type="file" class="btn btn-default btn-xs"></p>
<p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
</div>
</form>
我希望它会发送 post 请求,flask 会捕获它并按照此文件中所示进行文件上传:
from flask import render_template, request, Response, url_for
from app import app
from werkzeug import secure_filename
## uploading specs ##
UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = set(['deb'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
## index page stuff ##
@app.route('/index', methods = ['GET', 'POST'])
def index():
## kerberos username
secuser = request.environ.get('REMOTE_USER')
user = { 'nick': secuser }
## file uploading stuff
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
return redirect(url_for('/index',
filename=filename))
## main return
return render_template("index.html",
user = user)
上传文件按钮运行良好,一切正常,只是当按下提交按钮时出现 400 错误,所以它必须是 flask 方面的东西,但我不太确定它可能是什么。
任何帮助将不胜感激:)
最佳答案
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join("/tmp/", filename))
这就是诀窍!
尽管您还需要将其添加到 index.html(将 name="file"添加到 upload_button)
<form id="package_form" action="" method="POST">
<div>
<p>Upload Packages:</p>
<p><input id="upload_button" type="file" class="btn btn-default btn-xs" name="file"></p>
<p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
</div>
</form>
关于python - 用于文件上传的 Flask/Apache 提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23964552/