使用HttpResponse在Django中下载文件名中包含中文字符的文件

3
我想使用 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 和其他浏览器中分别使用 urlquotesmart_str 来解决。


1
你尝试过不调用urlquote吗? - jpic
是的,但如果没有使用urlquote,会显示Unicode错误。 - Angelia
你应该用 "attachment" 替换 "u"attachment 我认为... 还应该尝试使用 force_unicode 而不是 urlquote(来自 django.utils.encoding import force_unicode) - jpic
我使用了smart_str,它很有效,谢谢!!! - Angelia
浏览器兼容性在Content-Disposition方面很混乱,请参考https://dev59.com/SXVD5IYBdhLWcg3wGHeu#216777 - bronze man
4个回答

2
我认为它可能与编码翻译字符串有关。
请尝试这个:
    from django.utils.encoding import smart_str, smart_unicode
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
    return response

2
以下代码对我来说可以解决你的问题。
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

1
你是在说,“以下代码对我有效,可以解决你的问题”吗?如果是这样,请解释一下,以便OP可以将其应用到他们的问题上。 - sgress454

0

0

感谢铜人Kronel,我已经找到了一个可接受的解决方案:

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(链接到提供文件的视图)

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

请注意,文件名并不一定需要是一个参数。然而,上述代码将让您的函数知道它是什么。如果您在同一个函数中处理多个不同的内容类型,则非常有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接