Serving large files ( with high loads ) in Django

前端 未结 5 1313
耶瑟儿~
耶瑟儿~ 2020-12-04 13:00

I\'ve been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk

5条回答
  •  离开以前
    2020-12-04 13:13

    Your opening of the image loads it in memory and this is what causes the increase in load under heavy use. As posted by Martin the real solution is to serve the file directly.

    Here is another approach, which will stream your file in chunks without loading it in memory.

    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
    

提交回复
热议问题