[英]Empty download file from django view
I am using django 1.11.2 and I want to have view with downloadable file. 我正在使用django 1.11.2,我想查看可下载文件。 After click on link the file is downloading but file is empty and instead of png, I recieved empty txt file. 单击链接后,文件正在下载,但文件为空,而不是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
EDIT: 编辑:
value here response['Content-Length']
is http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg
这里的值response['Content-Length']
是http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg
Just pass the file in HttpResponse
constructor like this: 只需在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
From HttpResponse docs 来自HttpResponse文档
content should be an iterator or a string. 内容应为迭代器或字符串。 If it's an iterator, it should return strings, and those strings will be joined together to form the content of the response. 如果是迭代器,则应返回字符串,并将这些字符串连接在一起以形成响应的内容。 If it is not an iterator or a string, it will be converted to a string when accessed. 如果它不是迭代器或字符串,则在访问时将转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.