nadermx
nadermx

Reputation: 2776

Flask app behind gunicorn and nginx is only streaming files, not allowing for download

I currently have an app on a subdomain, called api.example.com and I have example.com putting a file with api.example.com in the HTML streams the file instead of sending it for downloads.

The HTML looks like so

<a href="https://api.example.com/path/to/file" download="https://api.example.compath/to/file">

I have also tried just <a href="https://api.example.com/path/to/file" download>

My flask route looks like this


CORS(app, headers='Content-Type')

@app.route('/static/downloads/<path:path>')
def generic_send_file(path):
    final_name = path.split('/')[-1]

    return send_from_directory(
        app.config['DOWNLOAD_FOLDER'],
        path,
        as_attachment=True,
        attachment_filename=final_name
    )

And my nginx route looks like this

    server_name api.example.com;
    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location /static {
        alias  /home/www/api/static/;
    }
    client_max_body_size 100000m;

And this is my gunicorn

[program:api]
command = /home/www/env/bin/gunicorn run:app -b localhost:8000
environment=PATH="/home/www/env/bin:%(ENV_PATH)s"
directory = /home/www/api
user = api
stdout_logfile = /var/log/api/api.out.log
stderr_logfile = /var/log/api/api.err.log

The flask app works on local. But when I put it live, it instead of sending the mp3 file to download, it opens it in the browser.

Any help would be appreciated.

Upvotes: 0

Views: 333

Answers (1)

nadermx
nadermx

Reputation: 2776

I had to put this into nginx route

    location /static/downloads/  {
                autoindex on;
                alias /home/www/api/static/downloads/;
                expires 30d;
                        if ( $request_filename ~ "^.*/(.+.*)$" ){
                        set $fname $1;
                        add_header Content-Disposition 'attachment; filename="$fname"';
        }
    }

Upvotes: 1

Related Questions