【问题标题】:HttpResponse content type for csv and other extentions doesn't work in firefox but works in Chrome and IEcsv 和其他扩展的 HttpResponse 内容类型在 Firefox 中不起作用,但在 Chrome 和 IE 中起作用
【发布时间】:2013-01-16 19:17:43
【问题描述】:

我正在使用 PYTHON+DJANGO 来实现一个文件共享系统。当用户尝试下载文件时,它在 Chrome 和 IE 中运行良好,但在 Firefox 中运行良好,如果 Firefox 无法识别扩展名(例如 .pl 和 .csv),则返回部分文件名并且不返回扩展名

查看

filename = os.path.join(MEDIA_ROOT, entry.myfile.url)
wrapper = FileWrapper(file(filename,'rb'))
response = HttpResponse(wrapper, content_type='application/octet-stream')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = "attachment; filename=" + entry.name

我尝试了 content_type=mimetypes.guess_type(filename) 但这并没有解决问题 我还尝试用句点替换文件名中的任何空格,这确实有效!但我确信有一个干净的解决方案!

【问题讨论】:

    标签: python django content-type httpresponse


    【解决方案1】:

    回答一个老问题,我知道,但实际问题是您没有用双引号将文件名括起来(它必须是双引号,而不是单引号)。 IE 和 Chrome 会读取到行尾,但 Firefox 会读取到第一个空格并停止。

    所以只需将 response['Content-Disposition'] = "attachment; filename=" + entry.name 更改为 response['Content-Disposition'] = 'attachment; filename="%s"'%(entry.name) 即可。

    【讨论】:

      【解决方案2】:

      基于django.views.static

      import mimetypes
      import os
      import stat
      from django.http import HttpResponse
      
      statobj = os.stat(fullpath)
      mimetype, encoding = mimetypes.guess_type(fullpath)
      mimetype = mimetype or 'application/octet-stream'
      
      with open(fullpath, 'rb') as f:
          response = HttpResponse(f.read(), mimetype=mimetype)
      
      if stat.S_ISREG(statobj.st_mode):
          response["Content-Length"] = statobj.st_size
      if encoding:
          response["Content-Encoding"] = encoding
      response['Content-Disposition'] = 'inline; filename=%s'%os.path.basename(fullpath)
      return response
      

      【讨论】:

      • 这与我的解决方法相同(用句点替换空格),因为在下载时空格被下划线替换。我试图允许在不更改名称的情况下下载文件。但是谢谢你的帮助:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2011-05-03
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 2017-10-13
      • 2013-12-30
      相关资源
      最近更新 更多