有些时候需要先检查用户权限再下载文件,这个时候就可以通过django来实现了
Django提供了StreamingHttpResponse对象用于将文件流发送给浏览器,与HttpResponse对象非常相似,对于文件下载功能,使用StreamingHttpResponse对象更合理。
先写一个迭代器,用于处理文件,然后将这个迭代器作为参数传递给StreaminghttpResponse对象
fromdjango.http import StreamingHttpResponse
deffile_download(request):
def file_iterator(file_name, chunk_size=512):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
the_file_name = " filename.pdf"
response =StreamingHttpResponse(file_iterator(the_file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
return response
为了让文件下载到硬盘,添加了如下两句:
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)