使用StreamingHttpResponse类
class DownloadFileView(View): """文件下载""" def get(self, request): file_id = request.GET.get("file_id", None) # 文件id
if file_id: media = Media.objects.get(id=file_id) # 查询数据库 real_path = settings.MEDIA_ROOT + media.url # 获取文件路径 # 使用StreamingHttpResponse进行大文件下载,不占内存 def file_iterator(file_path, chunk_size=8192): with open(file_path, 'rb') as file: while True: data = file.read(chunk_size) if not data: break yield data file_format = media.format response = StreamingHttpResponse(file_iterator(real_path)) if media.type == 1: # 图片下载 response['Content-Type'] = f'image/{file_format}' elif media.type == 2: # 视频下载 response['Content-Type'] = f'video/{file_format}' # 下载时显示文件的大小 response['Content-Length'] = str(file_size) elif media.type == 3: # 其他类型文件下载 response['Content-Type'] = 'application/octet-stream' # 使用quote对下载的中文文件名进行url编码,否则在Content-Disposition里的filename无法正确识别 encoded_string = quote(f'{media.title}.{file_format.lower()}') response['Content-Disposition'] = f'attachment; filename="{encoded_string}"' return response
AI写代码 python 运行
为DownloadFileView类视图配置url后请求时就可以直接下载了
原文链接:https://blog.csdn.net/qq_37...
使用StreamingHttpResponse类
class DownloadFileView(View):
"""文件下载"""
def get(self, request):
file_id = request.GET.get("file_id", None) # 文件id
AI写代码
python
运行
为DownloadFileView类视图配置url后请求时就可以直接下载了
原文链接:https://blog.csdn.net/qq_37...