A
A
Artem2019-06-25 11:08:56
Python
Artem, 2019-06-25 11:08:56

How to download files using flask?

You need to download the file from the server. The user needs to be given access to a specific directory on the server, from where he can select the file he wants to download. How can this be done through fkask?
That is, how can I let the user select a file to pass it to send_file()?

from flask import send_file
@app.route('/download_file')
def download_file():
    return send_file('table.xlsx')

Or how can I make a form to select a file in html?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-06-25
@deepblack

The user needs to be given access to a specific directory on the server, from where he can select the file he wants to download.

Build a tree like
So
def make_tree(path):
    tree = dict(name=path, children=[])
    try: lst = os.listdir(path)
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = os.path.join(path, name)
            if os.path.isdir(fn):
                tree['children'].append(make_tree(fn))
            else:
                tree['children'].append(dict(name=fn))
    return tree

Output the result in the template, with a link to /uploads/path/filena.me
here catch the directory and file name and give it to the user
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

Implement the details yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question