4

I am trying to download the file using flask. my code is as follows

@app.route('/Download')
def Down():
    rpm = request.args.get('rpm')
    root = '/home/rpmbuild/RPMS/'
    return send_from_directory(root,rpm)

The name of the file is passed in the url. when i hit the url, I am able to download the file but the name of the file in always Download. i need it to be actual name of the file. I have also tried send_file() but it is also downloading it with the name Download.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Usama
  • 480
  • 4
  • 15

1 Answers1

3

The "options" of send_from_directory are the same as sendfile:

flask.send_file(filename_or_fp, mimetype=None, as_attachment=False,
                attachment_filename=None, add_etags=True,
                cache_timeout=None, conditional=False,
                last_modified=None)

So you should call it with:

@app.route('/Download')
def Down():
    rpm = request.args.get('rpm')
    root = '/home/rpmbuild/RPMS/'
    return send_from_directory(root,rpm,attachment_filename='foo.ext')

Where you of course substitute 'foo.ext' by the name you want to give the file. You probably also want to set the as_attachment parameter to True.

In case you want the same name, you can use os.path.basename(..) for that:

import os

@app.route('/Download')
def Down():
    rpm = request.args.get('rpm')
    root = '/home/rpmbuild/RPMS/'
    return send_from_directory(root,rpm,as_attachment=True,
                               attachment_filename=os.path.basename(rpm))
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555