How to pass uploaded image to template.html in Flask
From the uploaded_file function, we head to the template.html and there will are redirected back <img src="{{ url_for('send_file', filename=filename) }}">
coming back we hit the send_file function which will show the content of the HTML inside the template with image uploaded and stored in the UPLOAD_FOLDER specified. you are also missing from werkzeug import secure_filename
this in py file
@app.route('/show/<filename>')
def uploaded_file(filename):
return render_template('template.html', filename=filename)
@app.route('/uploads/<filename>')
def send_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
Now your template.html will look like this..
<!doctype html>
<title>Hello from Flask</title>
{% 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 %}
What's happening now is that /uploads/foo.jpg
returns the HTML inside template.html. There you try to use /uploads/foo.jpg
as the source of the img tag. Nowhere you serve the actual image out.
Let's modify it like this: /show/foo.jpg
returns the HTML page and and /uploads/foo.jpg
returns the image. Replace the latter route with these two and you should be good to go:
@app.route('/show/<filename>')
def uploaded_file(filename):
filename = 'http://127.0.0.1:5000/uploads/' + filename
return render_template('template.html', filename=filename)
@app.route('/uploads/<filename>')
def send_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)