【问题标题】:Downloading a file with Chinese characters in the name in Django with HttpResponse使用HttpResponse在Django中下载名称中包含中文字符的文件
【发布时间】:2012-03-02 09:46:36
【问题描述】:

我想用 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解决。

【问题讨论】:

  • 你试过不调用 urlquote 吗?
  • 可以,但是没有urlquote,会显示unicode错误
  • 我认为您应该将“attachment by u”替换为...也可以尝试 force_unicode 而不是 urlquote(来自 django.utils.encoding import force_unicode)
  • 我使用 smart_str,它可以工作,谢谢!!!
  • 浏览器兼容性是Content-Disposition一团糟,请看stackoverflow.com/a/216777/1586797

标签: django file download cjk


【解决方案1】:

我觉得可能和Encoding Translated Strings有关

试试这个:

    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
    

    【讨论】:

    • 你是说“下面的代码可以解决你的问题”吗?如果是这样,您能否解释一下 OP 如何将其应用于他们的问题?
    【解决方案3】:

    在 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

    【讨论】:

      【解决方案4】:

      感谢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-Type,则很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-03
        • 2016-02-06
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        • 2019-07-06
        • 2020-03-22
        相关资源
        最近更新 更多