Flask/Werkzeug how to attach HTTP content-length header to file download


I am using Flask (based on Werkzeug) which uses Python.

The user can download a file, I'm using the send_from_directory-function.

However when actually downloading the file, the HTTP header content-length is not set. So the user has no idea how big the file being downloaded is.

I can use os.path.getsize(FILE_LOCATION) in Python to get the file size (in bytes), but cannot find a way to set the content-length header in Flask.

Any ideas?

10/29/2012 1:03:10 PM

Accepted Answer

I believe you'd do something like this (untested):

from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))

See: Werkzug's Headers object and Flask's Response object.

12/1/2013 2:16:04 PM

I needed this also, but for every requests, so here's what I did (based on the doc) :

def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow