I'm building a image recognition Flask project. And I want the image shown on the web page. Here is the structure of my project:
As you can see, static
,templates
and upload
are in the same folder. If I save the image into static
folder (which is generated by the VS2015 flask project) and write the result.html
like this:
<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<title>Flood Classifier</title>
</head>
<body>
<img src="{{url_for('static', filename=thename)}}">
</body>
</html>
The image would shown successfully when this Python function is called:
@app.route('/classify', methods=['POST','GET'])
def classify():
global image
image = np.expand_dims(image, axis = 0)
result = model.predict(image)
if result[0][0] == 1:
result = "flood"
else:
result = "no flood"
return render_template('result.html', thename = imagename, outcome_info = result)
However, if I save the image file into upload
(which is created by myself), and just change the folder name in result.html
like this:
<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<title>Flood Classifier</title>
</head>
<body>
<img src="{{url_for('upload', filename=thename)}}">
</body>
</html>
The image would not shown when call that Python function. Do the images must be saved into static
folder or there is something that I misunderstand?
you can use this configuration:
from flask import Flask
app = Flask(__name__, static_url_path = "/upload", static_folder = "upload")
Then you can access your images as follows:
<img src='/upload/image1.jpg' width="200" height="85">
check this answer for more details: Cannot show image from STATIC_FOLDER in Flask template
I think you misunderstand how url_for
works.
The first parameter is endpoint
, endpoint
is roughly a registered route handler. And static
is a built-in route handler which handles all requests to http://yourserver/static/xxxx
.
When you set static_folder
, you set the flask to serve all files under that folder through route static
. You can also override this default route by setting static_url_path
.
doc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With