Skip to content

Instantly share code, notes, and snippets.

@jlaine
Last active July 5, 2018 07:57
Show Gist options
  • Save jlaine/e62f7b7c57cd17997ff1af2058f91667 to your computer and use it in GitHub Desktop.
Save jlaine/e62f7b7c57cd17997ff1af2058f91667 to your computer and use it in GitHub Desktop.
from urllib.parse import quote
def add_content_disposition_header(response, filename):
"""
Add an RFC5987 / RFC6266 compliant Content-Disposition header to an
HttpResponse to tell the browser to save the HTTP response to a file.
"""
try:
filename.encode('ascii')
file_expr = 'filename="{}"'.format(filename)
except UnicodeEncodeError:
file_expr = "filename*=utf-8''{}".format(quote(filename))
response['Content-Disposition'] = 'attachment; {}'.format(file_expr)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment