Rome
Rome

Reputation: 603

Download File From Another Directory In Flask

Im New In Flask . I'm try to make download list of /var/ directory files but i can't find any way to make this link . any file could be in this directory so tempfile could solve this problem . i don't know the file so i can't copy file in flask directory , could any one tell me how can i make download link for file like this ?

Upvotes: 1

Views: 3324

Answers (1)

djangulo
djangulo

Reputation: 96

I've never used flask, but have some experience with Django. From quickly looking at the flask docs (rendering_templates) you would have to pass a context variable to the rendering function, then add it to the jinja template.

I would also suggest designating a different folder to place downloads, as giving users access to your /var/ folder can pose a security concern.

See below:

import os

from flask import Flask, render_template

app = Flask(__name__)

dloads_dir = '/var/www/mysite/downloads/'
dloads = os.listdir(dloads_dir).sort()
dloads_src = ['/downloads/{}'.format(i) for i in dloads]

@app.route('/Downloads')
def list_downloads():

    return render_template('downloads.html', dloads=dloads, dloads_src=dloads_src)

Then in the html (should I say Jinja2) template:

<!doctype html>
<title>Hello from Flask</title>
{% for file in dloads %}
    <a href="{{ dloads_src[loop.index0] }}" download>{{ file }}</a>
{% endfor %}
</html>

Here's where I found the loop.index method

(1) Edit: Fixed my bad html

Upvotes: 4

Related Questions