How to encode UTF8 filename for HTTP headers? (Python, Django)

前端 未结 6 853
温柔的废话
温柔的废话 2020-11-28 04:18

I have problem with HTTP headers, they\'re encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII.

response[\'Cont         


        
6条回答
  •  孤街浪徒
    2020-11-28 04:53

    I can say that I've had success using the newer (RFC 5987) format of specifying a header encoded with the e-mail form (RFC 2231). I came up with the following solution which is based on code from the django-sendfile project.

    import unicodedata
    from django.utils.http import urlquote
    
    def rfc5987_content_disposition(file_name):
        ascii_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore').decode()
        header = 'attachment; filename="{}"'.format(ascii_name)
        if ascii_name != file_name:
            quoted_name = urlquote(file_name)
            header += '; filename*=UTF-8\'\'{}'.format(quoted_name)
    
        return header
    
    # e.g.
      # request['Content-Disposition'] = rfc5987_content_disposition(file_name)
    

    I have only tested my code on Python 3.4 with Django 1.8. So the similar solution in django-sendfile may suite you better.

    There's a long standing ticket in Django's tracker which acknowledges this but no patches have yet been proposed afaict. So unfortunately this is as close to using a robust tested library as I could find, please let me know if there's a better solution.

提交回复
热议问题