简体   繁体   English

数据库中带有非ASCII字符的Django文件名

[英]Django filename from database with non-ascii characters

I'm trying to create a file dynamically in Django: 我正在尝试在Django中动态创建文件:

response = HttpResponse(mimetype='text/txt')
response['Content-Disposition'] = 'attachment; filename=%s' % filename # UnicodeEncodeError

response.write('text')

return response

If I hardcode the filename it works properly, but if I try to create the filename from DB data that contains non-ascii characters (like ó) I get a UnicodeEncodeError exception. 如果我对文件名进行硬编码,则它可以正常工作,但是,如果我尝试从包含非ASCII字符(如ó)的数据库数据中创建文件名,则会收到UnicodeEncodeError异常。 How can I use the DB filename without getting an exception? 如何在没有异常的情况下使用数据库文件名?

from django.utils.encoding import smart_str
...

 response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)

You can fix the problem on the Django side but there is no guarantee it will work in all browsers. 您可以在Django端解决此问题,但不能保证它会在所有浏览器中正常工作。

See the testcases at http://greenbytes.de/tech/tc2231/ . 请参阅http://greenbytes.de/tech/tc2231/上的测试用例。

For more details on this see this question , which links to a snippet to handle most cases. 有关此问题的更多详细信息,请参见此问题该问题链接到一个片段以处理大多数情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM