Get Flask To Show Image Not Located In The Static Directory
Solution 1:
Look like you have file system path instead site. When you start resource with /
then path will start from site root (absolute path for site, without slash or with ./
or ../
is relative) for example if you have site http://test.com
then /
will be http://test.com/
or /test
will be http://test.com/test
. You can set path with specific protocol protocol://
or identical for current site //
for another sites. You always can found errors with wrong (full) urls in your browser error console.
To get access to file system you must use file://
protocol and you urls will be like file:///Users/Darrell/Pictures/...
. But it will work only for your computer and can have security issues. You also can set symbolic link for this files to static folder and this resolve security issues, but not resolve issue with only your computer. To completely resolve this issue better publish this files to your application or on public (private) web servers for images or another static.
Solution 2:
So here is my project path. I wrote a simple function that would work by allowing it to render on the webpage. I am not a 100% sure if it would work once deployed, so I will update if it does work when deployed.
<img alt="" src="{{ url_for('send_file', filename=image_url) }}"id ="img"/>
This is the code of the HTML element and here is its corresponding code in Python on the server side.
defgetImageName(x):
"""
Dealing with Unix Path names and Windows PathNames
"""if platform.system() == 'Linux':
return x[x.rfind("/")+1:]
return x[x.rfind("\\")+1: ]
defgetFolder(x):
y = []
if platform.system() == 'Linux':
y = x.split("/")
else:
y = x.split("\\")
# print(y)
cat_name = ""if"roomImage"in x:
cat_name+="roomImage/" + y[-2]
elif"lobbyImage"in x:
cat_name+="lobbyImage"elif"miscImage"in x:
cat_name += "miscImage/" + y[-2]
elif"washroomImage"in x:
cat_name += "washroomImage"else:
cat_name += "facadeImage"return cat_name + "/"@app.route("/send_file/<filename>")defsend_file(filename):
return send_from_directory(app.config["UPLOAD_FOLDER"] +"/" + getFolder(filename) , getImageName(filename))
This works for the most part. By the way, image_url is supposed to the be the absolute path of the image that you can pass as an argument to the Jinja2 template via render_template like so:
return render_template("/contentpage.html",image_url=imgurl)
Don't forget to import send_from_directory and set app.config["UPLOAD_FOLDER"] to the appropriate directory. This isn't the most efficient way to do it
Post a Comment for "Get Flask To Show Image Not Located In The Static Directory"