我在apache后面运行了一个烧瓶应用程序,在我的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>
我希望发送帖子请求并且烧瓶会抓住它并按照此文件中所示进行文件上传:
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错误,所以它必须是事情的一部分,但是我&# 39;我不确定它可能是什么。
非常感谢任何帮助:)
答案 0 :(得分:1)
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>
答案 1 :(得分:0)
当您在表单中包含文件输入时,您需要将enctype="multipart/form-data"
添加到表单标记本身,以告知浏览器以正确的格式发送内容。