Home > database >  Flask Images in Various Subfolders
Flask Images in Various Subfolders

Time:02-23

I have a simple Flask web application which stores small PDFs / JPEGs for each user. Since the files are unique to each user, I do not want to simply store them in the "static" folder as flask requires. Instead, I have a "Users" folder, within which a subfolder is created for each user & their files are stored.

I want to be able to do the following, but the image does not display:

{% block main %}
   <img src="/users/bob/test.JPG"
{% endblock %}

However, if i save that same test.JPG in static and use the following, it does work:

{% block main %}
   <img src="/static/test.JPG"
{% endblock %}

My file structure is:

ProjectFolder
   static
      styles.css
   templates
      index.html
      ...
   users
      bob
         image.jpg
         ...
      sam
      ...
   venv
   app.py
   helpers.py

CodePudding user response:

Flask only supports downloading static files from the static folder by default.
However, if you add your own endpoint, you can download files from a folder of your choosing. For security reasons, you should ensure that access to certain regions of your file system is limited. I also recommend using a subdirectory of the instance path for this. Thus, the files are separated from your application.

import os
from flask import Flask 
from flask import send_from_directory

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(app.instance_path, 'users')

try:
    os.makedirs(app.config['UPLOAD_FOLDER'])
except OSError:
    pass

@app.route('/users/<path:filename>')
def download(filename):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'], 
        filename
    )

To request one of the files, you can either use url_for or specify the path directly.

<img src="{{ url_for('.download', filename='bob/image.jpg' }}" />
  • Related