Issue
I'm setting an application where I need to display some image. My images are located outside of my app's folder, that's why I've used this:
@app.route('/<path:filename>')
def download_file(filename):
return send_from_directory(MEDIA_FOLDER, filename=filename, as_attachment=True)
The architecture of my folders is:
--images1
|__ image1.png
|__ image2.png
--images2
|__ image3.png
|__ image4.png
--web
|__ app.py
|__ templates
|__ index.html
I've stored all my images path in a list as:
images_path = ['image1.png', 'image2.png', ...]
At the moment, I've tried to display the images as:
{% for image in images_path %}
<img src="{{ url_for('download_file', filename="{{ image }}") }}">
Using this, it displays always the same image. In my example the image1.png
.
I've tried to check if the for loop works, and it works.
I've tried this:
{{ image }} CHECKER
<img src="{{ url_for('download_file', filename="{{ image }}") }}">
and it displays on my page:
>>>
image1.png CHECKER then the `image1.png`
image2.png CHECKER but also `image1.png`
UPDATE 1
In my app.py, I've added this:
@app.route('/<path:filename>')
def download_file(filename):
images_folder = [images1, images2]
try:
for image_folder in imagesfolder:
MEDIA_FOLDER = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + str(image_folder) + "\\"
return send_from_directory(MEDIA_FOLDER, filename=filename, as_attachment=True)
except FileNotFoundError:
abort(404)
and on my template.html, I've added this:
{% for image in images_path %}
<img src="{{ url_for('download_file', filename=image) }}">
How can I correctly set the path here? How can I link the images and its directory?
UPDATE 2
I've changed my script by:
@app.route('/<path:filename>')
def download_file(filename):
try:
return send_file(filename, as_attachment=True)
except FileNotFoundError:
abort(404)
The filename will be defined by:
>>>> filename = str(os.getcwd()) + str(list_machine[i]) + str(elem)
When I inspect the elements on my page, the URL seems to be right but the image is not displayed.
How can I display all the images stored in my folders?
Thanks in advance.
Solution
You could try this:
<img src="{{ url_for('download_file', filename=image) }}">
with the image
variable defined as: image = str(os.getcwd()) + '/path/to/image'
You must define this variable by listing your files, you can use: os.listdir('path/directory')
.
Your function named download_file
should be:
@app.route('/<path:filename>')
def download_file(filename):
try:
filename=os.path.join(app.root_path, filename)
return send_file(filename)
except FileNotFoundError:
abort(404)
Don't forget to import the send_file
function.
It works for me. Hope it helps.
Answered By - Bando
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.