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

时间:2012-03-02 09:46:36

标签: django file download cjk

我想用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和其他浏览器中以不同的方式使用urlquotesmart_str解决。

4 个答案:

答案 0 :(得分:2)

我认为这可能与Encoding Translated Strings

有关

试试这个:

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

答案 1 :(得分: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

答案 2 :(得分:0)

在Content-Disposition中没有可互操作的方式来编码非ASCII名称。 Browser compatibility is a mess.

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

请查看https://stackoverflow.com/a/216777/1586797

答案 3 :(得分:0)

感谢bronze manKronel,我已经找到了解决此问题的可接受方案:

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>

请注意,文件名实际上不一定是参数。但是,上面的代码将让您的函数知道它是什么。如果您在同一个函数中处理多个不同的Content-Types,则非常有用。