您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Django中提供大文件(高负载)

在Django中提供大文件(高负载)

打开图像会将其加载到内存中,这就是导致大量使用情况下负载增加的原因。正如Martin所说,真正的解决方案是直接提供文件

这是另一种方法,它将以分块方式流式传输文件而不将其加载到内存中。

import os
import mimetypes
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper


def download_file(request):
   the_file = '/some/file/name.png'
   filename = os.path.basename(the_file)
   chunk_size = 8192
   response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size),
                           content_type=mimetypes.guess_type(the_file)[0])
   response['Content-Length'] = os.path.getsize(the_file)    
   response['Content-Disposition'] = "attachment; filename=%s" % filename
   return response
Go 2022/1/1 18:19:47 有480人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶