Django--StreamingHttpResponse下载文件
from django.shortcuts import render, HttpResponse from django.http import StreamingHttpResponse import os def index(request): return render(request,"index.html") # Create your views here. def file_down(request, id): """ 下载压缩文件 :param request: :param id: 数据库id :return: """ data = [{"id":"1","image":"animation.jpg"}] # 模拟mysql表数据 file_name = "" # 文件名 for i in data: if i["id"] == id: # 判断id一致时 file_name = i["image"] # 覆盖变量 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录 file_path = os.path.join(base_dir, 'upload','images', 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
代码解释:
index是默认的首页展示
file_down 是用来做下载的。
为了简单实现,在file_down 中的data,表示数据库中的记录。需要指定id才能对应的文件!
其他代码,有详细的注释,这里就不多介绍了
修改index.html,注意:这里需要指定id。这里仅做示例,固定了id。
实际情况应该查询数据库,使用Django模板引擎来渲染的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/download/1/">下载图片</a> </body> </html>
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/WG11/p/Django_StreamingHttpResponse_download.html,作者:def_Class

浙公网安备 33010602011771号