Skip to content

Instantly share code, notes, and snippets.

@tlebel
Created July 10, 2012 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tlebel/3085973 to your computer and use it in GitHub Desktop.
Save tlebel/3085973 to your computer and use it in GitHub Desktop.
Encode HTTP content-disposition filename in base64 or URL Encode
from django.utils.encoding import iri_to_uri
import base64, math
def __get_content_disposition(request, nom_fichier):
"""
Permet de générer la bonne chaine de caractère, selon le navigateur représentant le nom du fichier
"""
if "Firefox/" in request.META['HTTP_USER_AGENT'] or "Chrome/" in request.META['HTTP_USER_AGENT']:
# FF et Chrome: aiment le format base64 splitté en petits blocs
# attachment; filename="=?UTF-8?B?VW4gZmljaGllciBzcMOpY2lhbCBhdmVjIGFjY2VudCBtYWlzIA==?= =?UTF-8?B?YXZlYyB1biB0csOocyBsb25nIG5vbSBkZSBmaWNoaWVyLnR4dA==?="
str_size = 30
nom_b64 = ""
for i in range(0,int(math.ceil(len(nom_fichier)/float(str_size)))):
if nom_b64 != "":
nom_b64 += "=?UTF-8?B?"
nom_b64 += base64.urlsafe_b64encode(nom_fichier[i*str_size: (i+1)*str_size]) + "?= "
return 'attachment; filename="=?UTF-8?B?%s"' % nom_b64
else:
# IE9 et les autres: préfèrent format URL Encode
# attachment; filename="Un%20fichier%20sp%C3%A9cial%20avec%20accent%20mais%20avec%20un%20tr%C3%A8s%20long%20nom%20de%20fichier.txt"
return 'attachment; filename="%s"' % iri_to_uri(nom_fichier)
@jbdemonte
Copy link

J'ai fais une petite modif pour gerer les caracteres chinois (utf-8) ainsi qu'un petit clean de la methode de split du nom
et comme les pull request n'existe pas sur gist... si tu veux te mettre a jour
https://gist.github.com/4509001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment