I am using a flask app which is running on my machine (local server). I want to perform this task:
The user chooses an image and that image is rendered to a template.
I do not want to upload the image file to any folder. Many questions were answered based on how the user chooses an image and uploads it to a different folder.
Instead, all I want to do is get the image from form input and display it in the browser.
I have referred a number of resources: 1. https://www.youtube.com/watch?v=Y2fMCxLz6wM 2. How to pass uploaded image to template.html in Flask 3. Post values from an HTML form and access them in a Flask view
However, all of them mostly mention about uploading images to a folder before displaying
This is my main.py
@app.route("/")
def index():
return render_template('index.html')
@app.route("/display", methods=['POST', 'GET'])
def display():
filename = request.form.get("file")
return render_template("display.html", image_name=filename)
index.html
<form id="display-img" action="http://localhost:5000/display" enctype=multipart/form-data method="POST">
<p>Image Select
<input type="file" name="file" accept="image/*"></p>
<button>SUBMIT</button>
</form>
display.html
<body>
{% extends "template.html" %}
{% block content %}
<h1> Displayed here </h1>
<img id="blah" src=" {{ url_for('display', file=image_name)}}">
{% endblock %}
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
</script>
The actual output is:
The user should be able to choose an image from a folder (index.html). When I hit submit, the template display.html is getting rendered but the image is a broken link image symbol
What I expect is:
The user should be able to choose an image from a folder (index.html). When I hit submit, it is rendered to display page (display.html).
I've tried different ways to pass the image name variable to the display path, but I am still not getting the image rendered correctly. This is how the rendered page looks so far
edit: added the code for JS in display.html