Last active
June 4, 2016 17:33
-
-
Save sauditore/ba23d0f3e0fa0b514f5d to your computer and use it in GitHub Desktop.
Simple Download Handler For Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
__author__ = 'saeed.auditore' | |
import mimetypes | |
import os | |
from django.http import HttpResponse | |
def respond_as_attachment(request, file_path, original_filename): | |
if original_filename is None: | |
original_filename = 'unknown_file' | |
fp = open(file_path, 'rb') | |
response = HttpResponse(fp.read()) | |
fp.close() | |
type, encoding = mimetypes.guess_type(original_filename) | |
if type is None: | |
type = 'application/octet-stream' | |
response['Content-Type'] = type | |
response['Content-Length'] = str(os.stat(file_path).st_size) | |
if encoding is not None: | |
response['Content-Encoding'] = encoding | |
# To inspect details for the below code, see http://greenbytes.de/tech/tc2231/ | |
if u'WebKit' in request.META['HTTP_USER_AGENT']: | |
# Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly. | |
filename_header = 'filename=%s' % original_filename.encode() | |
elif u'MSIE' in request.META['HTTP_USER_AGENT']: | |
# IE does not support internationalized filename at all. | |
# It can only recognize internationalized URL, so we do the trick via routing rules. | |
filename_header = '' | |
else: | |
# For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers). | |
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(original_filename.encode()) | |
response['Content-Disposition'] = 'attachment; ' + filename_header | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment