从django视图清空下载文件

时间:2018-02-14 15:51:41

标签: python django file view download

我正在使用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

1 个答案:

答案 0 :(得分:0)

只需在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

  

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