【问题标题】:Empty download file from django view从 django 视图中清空下载文件
【发布时间】:2018-02-14 15:51:41
【问题描述】:

我正在使用 django 1.11.2,我想查看可下载文件。单击链接后,文件正在下载,但文件为空,而不是 png,我收到的是空的 txt 文件。

def download_file(request, uuid):
    response = HttpResponse(content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(models.DownloadLink.objects.get(uuid=uuid).download_file.file)
    response['Content-Length'] = 'http://{}{}'.format(Site.objects.get_current(), models.DownloadLink.objects.get(uuid=uuid).download_file.file.url)    
    return response

编辑:

这里response['Content-Length'] 的值是http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg

【问题讨论】:

    标签: python django file view download


    【解决方案1】:

    只需像这样在HttpResponse 构造函数中传递文件:

    def download_file(request, uuid):
        file = models.DownloadLink.objects.get(uuid=uuid).download_file
        response = HttpResponse(file.file, content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file.file)
        response['Content-Length'] = 'http://{}{}'.format(Site.objects.get_current(), file.file.url)    
        return response
    

    来自HttpResponse docs

    content 应该是一个迭代器或一个字符串。如果它是一个迭代器,它 应该返回字符串,这些字符串将被连接在一起 形成响应的内容。如果它不是迭代器或 字符串,访问时会转换为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多