我想用 Django 的 httpresponse
方法下载一个文件。文件名有一些特殊字符,比如中文。我可以使用以下代码下载文件,但文件名显示为“%E6%B8%B8%E6%88%8F%E6%B5%8F%E8%A7%88%E5%99%A8%E6% B3%A8%E5%86%8C%E9%A1%B5%E9%9D%A2.jpg".
谁能告诉我如何转换文件名?
response = HttpResponse(attachment.file, content_type='text/plain',mimetype='application/octet-stream')
response['Content-Disposition'] = "attachment; filename="+urlquote(filename)
return response
编辑:
使用smart_str
时又出现了一个问题,文件名在Firefox和Chrome中可以正常显示,但在IE中不能:在IE中仍然显示一些未知字符。有谁知道如何解决这个问题?
提前致谢!
---通过在IE和其他浏览器中使用urlquote
和smart_str
解决
最佳答案
我觉得可能和Encoding Translated Strings有关
试试这个:
from django.utils.encoding import smart_str, smart_unicode
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
return response
关于django - 使用HttpResponse在Django中下载名称中包含中文字符的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9531067/