【问题标题】:Django download file emptyDjango下载文件为空
【发布时间】:2011-03-09 16:09:46
【问题描述】:

我正在编写一个简单的函数,用于将某个文件从服务器下载到我的机器。 该文件由其 id 表示是唯一的。文件正确定位,下载完成,但下载的文件(虽然命名为服务器上的文件)是空的。 我的下载功能是这样的:

def download_course(request, id):
    course = Courses.objects.get(pk = id).course
    path_to_file = 'root/cFolder'
    filename = __file__ # Select your file here.                                
    wrapper = FileWrapper(file(filename))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)

    return response

我哪里错了?谢谢!

【问题讨论】:

    标签: django file download sendfile


    【解决方案1】:

    尝试以下方法之一:

    1) 如果您正在使用 GZipMiddleware,请禁用它;

    2) 将补丁应用到 django/core/servers/basehttp.py 中描述 https://code.djangoproject.com/ticket/6027

    【讨论】:

      【解决方案2】:

      我回答了这个问题here,希望对您有所帮助。

      【讨论】:

      • 这个答案对我有帮助! (赏金将在 22 小时内提供 - 正如我今天开始的那样,并且可以在至少 22 小时内接受答案)
      【解决方案3】:

      看起来你没有发送任何数据(你甚至没有打开文件)。

      Django 有一个很好的发送文件的包装器(代码取自djangosnippets.org):

      def send_file(request):
          """                                                                         
          Send a file through Django without loading the whole file into              
          memory at once. The FileWrapper will turn the file object into an           
          iterator for chunks of 8KB.                                                 
          """
          filename = __file__ # Select your file here.                                
          wrapper = FileWrapper(file(filename))
          response = HttpResponse(wrapper, content_type='text/plain')
          response['Content-Length'] = os.path.getsize(filename)
          return response
      

      所以你可以使用response = HttpResponse(FileWrapper(file(path_to_file)), mimetype='application/force-download')之类的东西。

      如果你真的在使用 lighttpd(因为"X-Sendfile" 标头),我猜你应该检查服务器和 FastCGI 配置。

      【讨论】:

      • 嗨,抱歉耽搁了。我已经编辑了新的代码作品,但它实际上下载了我的脚本:D 当然是因为那个文件。我应该用什么替换那个 file 才能使下载正确?谢谢!
      • 嗯,__file__ 当然是 Python 脚本文件名。您需要将其替换为应该下载的文件的文件名(我猜这与课程有关)。
      • hmm .. 我猜是这样,我已经用 course 替换了它,其中 course 是链接 course = Courses.objects.get(pk = id).course 但我的错误是: 强制转换为 Unicode:需要字符串或缓冲区,找到 FieldFile
      • 在我的示例中,您必须提供文件名。如果你真的有一个FileFieldcourse 将是一个类似文件的对象 (docs.djangoproject.com/en/dev/ref/models/fields/…),你可以在我的示例中将file(filename) 替换为course.open()。 .open
      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多