[Django]-Downloading a file with Chinese characters in the name in Django with HttpResponse

2👍

I think it may have something to do with Encoding Translated Strings

Try this:

    from django.utils.encoding import smart_str, smart_unicode
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
    return response
👤darren

2👍

The following code works for me to solve your problem.

from django.utils.encoding import escape_uri_path

response = HttpResponse(attachment.file, content_type='text/plain',mimetype='application/octet-stream')

response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename))
return response

0👍

There is no interoperable way to encode non-ASCII names in Content-Disposition. Browser compatibility is a mess.

/real_script.php/fake_filename.doc
/real_script.php/mot%C3%B6rhead   # motörhead

please look at https://stackoverflow.com/a/216777/1586797

0👍

Thanks to bronze man and Kronel, I have come to an acceptable solution to this problem:

urls.py:

url(r'^customfilename/(?P<filename>.+)$', views.customfilename, name="customfilename"),

views.py:

def customfilename(request, *args, filename=None, **kwds):
    ...
    response = HttpResponse(.....)
    response['Content-Type'] = 'your content type'
    return response

your_template.html (links to the view providing the file)

<a href="customfilename/{{ yourfancyfilename|urlencode }}.ext">link to your file</a>

Please note that filename doesn’t really need to be a parameter. However, the above code will let your function know what it is. Useful if you handle multiple different Content-Types in the same function.

👤velis

Leave a comment