Python--django 实现文件下载功能
class DownloadTextObject(object):
def __init__(self, request):
self.params = None
self.request = request
self.msg = ''
self.query = self.request.query_params
self.body = self.request.data
self.page = self.request.GET.get('page', 1)
self.size = self.request.GET.get('size', 10)
self.txt_name = self.request.GET.get('txt_name', None)
self.userid = request.user.id
self.status = 200
self.result = {}
self.total = 0
def file_down(self):
"""
下载压缩文件
:return:
"""
file_name = self.txt_name # 文件名
file_path = os.path.join(FILEPATH, file_name) # 下载文件的绝对路径
if not os.path.isfile(file_path): # 判断下载文件是否存在
return HttpResponse("Sorry but Not Found the File")
def file_iterator(file_path, chunk_size=512):
"""
文件生成器,防止文件过大,导致内存溢出
:param file_path: 文件绝对路径
:param chunk_size: 块大小
:return: 生成器
"""
with open(file_path, mode='rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
try:
# 设置响应头
# StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法
response = StreamingHttpResponse(file_iterator(file_path))
# 以流的形式下载文件,这样可以实现任意格式的文件下载
response['Content-Type'] = 'application/octet-stream'
# Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
except:
return HttpResponse("Sorry but Not Found the File")
return response
参考博客:https://blog.csdn.net/wen61995120/article/details/80311142