JohnWick
JohnWick

Reputation: 5149

Python + Flask Image Upload "No file part"

I am new to python/flask and am trying to upload an image for a users profile picture during registration. I've taken the backend flask code related to file uploads directly from their documentation found here. When I perform a registration, I receive the HTTP error:

Bad Request The browser (or proxy) sent a request that this server could not understand.

And in my python console:

no file part

I am using a bootstrap fork "Upload Image w Preview & Filename" found here. Here is my registration form:

<form action="/register" method="POST">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" class="form-control" name="username" id="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password" id="password" placeholder="Password">
  </div>
  <div class="form-group">
    <label for="confirm-password">Confirm Password</label>
    <input type="password" class="form-control" name="confirm-password" id="confirm-password" placeholder="Confirm Password">
  </div>
  <div class="form-group">
      <label>Profile Picture</label>
      <div class="input-group">
          <span class="input-group-btn">
              <span class="btn btn-default btn-file">
                <button class="btn btn-success">Browse…</button>
                  <input type="file" id="imgInp" name="file">
              </span>
          </span>
          <input type="text" class="form-control" readonly>
      </div>
      <img id='img-upload' style="margin-top: 10px;"/>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

And here is my backend/flask stuff.

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import secure_filename
import datetime
import os

UPLOAD_FOLDER = '/static/images'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
db = SQL("sqlite:///data.db")
Session(app)

@app.route('/register', methods=['POST'])
def register():
    username = request.form.get("username")
    password = request.form.get("password")
    row = db.execute("SELECT * FROM users WHERE username = :username", username=username)
    if not row:
        if 'file' not in request.files:
            flash('No file part')
            print("no file part")
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            print("no selected file")
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
        db.execute("INSERT INTO users (username, passwordHash, pictureUrl) VALUES (:username, :passwordHash, 'static/images/default.jpg')", username=username,passwordHash=generate_password_hash(password))
    else:
        return apology("Username already exists.")
    return redirect("/")

Upvotes: 1

Views: 3942

Answers (1)

mckuok
mckuok

Reputation: 754

Add the attribute enctype='multipart/form-data' to the form tag. As this attribute enforces the proper HTTP request handling of the form.

Upvotes: 5

Related Questions