1

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("/")

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, that did help. But now I receive another exception "FileNotFoundError: [Errno 2] No such file or directory: '/static/images/Screenshot_2018-03-20_16.28.40.png'" related to this line: file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) ./static/images/ does exist. Picture of my directory structure here: ibb.co/iWwYen
Your UPLOAD_FOLDER is an absolute path, not a relative path to the root of your project. Add a . in front to declare it as a relative path should solve the problem .
I had an issue with updates to Flask which mean that <form action="" method="post" class="form" enctype=" multipart/form-data" role="form"> was not accepted. I had to remove the space infront of the enctype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.