1

so.... I'm a beginner in python flask trying to make a dashboard.

I have a folder where my uploaded pictures are located.

structure:

manage.py  # this is where I run the program.
src
    |--pic
        |--items
            |-- pic_here.jpg

how should I set up so I could load the picture and get it into <img>?

I tried searching but all they showed was how to set up static folders. I don't think this is one for static, the pictures are what I upload via dashboard.

in other words, src/pic/items is where my saved images are located and how do I set my flask to load this picture?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
MrSolid51
  • 307
  • 1
  • 7
  • 17
  • pictures **are** static resources... `url_for` in a Jinja template would load them to HTML. – OneCricketeer Jan 05 '18 at 05:34
  • oh..... so... I have to put `{{ url_for() }}` part into the img src right? ok, think I got it. Thanks a lot. – MrSolid51 Jan 05 '18 at 05:46
  • 1) You need something in Flask to know where your images are located on disk. 2) You don't need to use `url_for`, but that is just one way. You will need some variable to render into the `src` attribute that is relative to the hosted URL, yes. This is where a static resource folder is necessary. For example, you wouldn't put `http://example-site.com/src/pic/items/pic_here.jpg`, it would probably just be like `http://example-site.com/pic/pic_here.jpg` – OneCricketeer Jan 05 '18 at 05:51
  • Refer https://stackoverflow.com/questions/28207761/where-does-flask-look-for-image-files – OneCricketeer Jan 05 '18 at 05:53

2 Answers2

6

When you create a 'static' folder, you can use url_for in jinja to load your pictures in html.

Put your pictures in: /app_homedirectory/static/PictureName.jpg

Then you can load your pictures in html with: <img src={{ url_for('static', filename='PictureName.jpg') }}>

This works out of the box, you just need to create a folder named 'static' and flask will recognize it.

add from flask import url_for to the file that contains the view of your rendered html document.

Joost Barendregt
  • 396
  • 3
  • 16
4

What i would advise is to create a view that serves the image (a simple API).

app = Flask(__name__, upload_folder='upload') 

@app.route('/img/<path:filename>') 
def send_file(filename): 
    return send_from_directory(app.upload_folder, filename)

This should get the job done, but you can check this question for more.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
booluw
  • 324
  • 5
  • 15