0

I'm attempting to create a page that takes in a user-submitted image, and automatically redirects them to a new page where the image is rendered. Much of my code is borrowed from here: How to pass uploaded image to template.html in Flask. But I can't seem to get it to work; I run into a 400: Bad Request. It seems to me that the image is not saving under /static/images, but I am not sure why.

Here is the submission form in index.html:

<form method="POST" action="{{ url_for('predict') }}" enctype="multipart/form-data">
    <label for="file-input" class="custom-file-upload">
        <i class="fa fa-cloud-upload"></i> Upload Image
    </label>
    <input name="image-input" id="file-input" type="file" align="center" onchange="this.form.submit();">
</form>

Here is my app.py code:

from flask import Flask, render_template, request, url_for, send_from_directory, redirect
from werkzeug import secure_filename
import os

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

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/predict/', methods=['POST', 'GET'])
def predict():
    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(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/show/<filename>')
def uploaded_file(filename):
    return render_template('classify.html', filename=filename)

@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)


if __name__ == '__main__':
    app.run(debug=True)

And finally, I try to render it in classify.html, with the following code:

  {% if filename %}
  <h1>some text<img src="{{ url_for('send_file', filename=filename) }}"> more text!</h1>
  {% else %}
  <h1>no image for whatever reason</h1>
  {% endif %}

Where am I going wrong here?

Flow Nuwen
  • 547
  • 5
  • 20

1 Answers1

0

Looks like I was missing an argument in my input: name=file in index.html. Adding that fixed the error. Altogether, the input line looks like this:

<input id="file-input" name=file type="file" align="center" onchange="this.form.submit();">

Flow Nuwen
  • 547
  • 5
  • 20