Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask/Apache submit button for file upload

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 :)

like image 936
user3693056 Avatar asked Feb 02 '26 04:02

user3693056


1 Answers

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>
like image 101
user3693056 Avatar answered Feb 04 '26 19:02

user3693056



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!