Reputation: 53
I have a flask application running behind apache, and on my index.html page I have a file upload button and a submit button, as seen here:
<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>
which I was hoping would send the post request and flask would catch it and do the file uploading as shown in this file:
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)
The upload file button works well, and does everything correctly, it's just that when the Submit button is pressed I get a 400 error, so it has to be something on the flask side of things, but I'm not exactly sure what it could be.
Any help would be much appreciated :)
Upvotes: 3
Views: 3564
Reputation: 53
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))
This does the trick!
Although you also need to add this to index.html (name="file" to the 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>
Upvotes: 1
Reputation: 599610
When you include a file input in your form, you need to add enctype="multipart/form-data"
to the form tag itself, to tell the browser to send things in the right format.
Upvotes: 0