20

In flask, how do I serve images that are not in the static folder?

I currently save the user uploaded photos on a directory that is outside the flask folder (On openshift, image currently saving in the data folder under app-root/data and the flask files are in app-root/repo/).

In my templates, how do i serve the image files ?

Using url_for, how do i reference these image files that are outside the flask folder?

- data/
 |
  -- uploads/
- repo/
 |
  -- app/
    |
     -- __init__.py

As you can see the data folder outside the flask app folder. How do i generate links to files stored in data/uploads (one level up) from the flask app directory is the question ?

davidism
  • 121,510
  • 29
  • 395
  • 339
Shankar ARUL
  • 12,642
  • 11
  • 68
  • 69

1 Answers1

39

You have the send_from_directory function that does what you want, what I would do is declare a constant called MEDIA_FOLDER with the path where the media files are located and then, the only thing you need to do is to call the function like this:

from config import MEDIA_FOLDER

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(MEDIA_FOLDER, filename, as_attachment=True)

Then, to invoke it, you just do this:

{{ url_for('download_file', filename='dogs.jpg') }}

You can have more info about this here.

soerface
  • 6,417
  • 6
  • 29
  • 50
Leandro Poblet
  • 1,424
  • 1
  • 14
  • 19
  • Thanks. Any idea how would i go about getting the link for the file using url_for ? – Shankar ARUL Nov 17 '14 at 14:45
  • @sarul I just edited the post, but basically you just have to do {{ url_for('download_file', filename='dogs.jpg') }}} for example. – Leandro Poblet Nov 17 '14 at 16:19
  • im trying to reference the url_for in the src part of my img tag and still cant seem to get it to work. I updated my question with the file structure. Im essentially trying to generate file paths for files stored in data/uploads from the flask app which is stored in another directory – Shankar ARUL Nov 17 '14 at 17:00
  • 2
    Check your MEDIA_FOLDER path, because the path should always be MEDIA_FOLDER + img/dogs.jpg for example, just like the url for static content works.For your app structure, the MEDIA_FOLDER should have something like this: `MEDIA_FOLDER = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'data')` – Leandro Poblet Nov 17 '14 at 17:31
  • Thanks Leandro for that. I was hardcoding the path of the media folder and couldnt get it to work. When i switched it with the os.path, dirname function you mentioned above, it worked ! – Shankar ARUL Nov 18 '14 at 23:52