J. Raji
J. Raji

Reputation: 143

Flask: How to get uploads folder path

I'm trying to get the uploads folder path.

UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

I upload the images in the path:

.
└── uploads
    └── img_articles
        └── 2017
            └── 02
                └── image.jpg

I want to use image.jpg in a Jinja Template

{% extends "layout.html" %}
{% block content %}
<div class="container">
  <img src="{{image_path}}" alt="">
</div>
{% endblock %}

What should I do?

Upvotes: 2

Views: 7624

Answers (1)

MrLeeh
MrLeeh

Reputation: 5589

Have a look at the Uploading Files Pattern in the information for the Pros.

Define a route for your uploads:

from flask import send_from_directory

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

In your template you can then use the route to get your filename

<img src="{{ url_for('uploaded_file', filename='yourimage.jpg') }}">

Upvotes: 3

Related Questions