django 大文件下载

使用fbv 方法

@login_required(login_url='/login')
def down(request):
    def file_iterator(fn, chunk_size=512):
        while True:
            c = fn.read(chunk_size)
            if c:
                yield c
            else:
                break
    fn = open("大文件.zip", 'rb')
    response = StreamingHttpResponse(file_iterator(fn))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="%s"' % quote("大文件.zip")
    return response

StreamingHttpResponse与HttpResponse 对比

HttpResponse会直接使用迭代器对象,将迭代器对象的内容存储城字符串,然后返回给客户端,同时释放内存。可以当文件变大看出这是一个非常耗费时间和内存的过程。

StreamingHttpResponse是将文件内容进行流式传输,数据量大可以用这个方法

其中  文件名为中文时要 需要转化格式   

from urllib.parse import unquote, quote

filename = quote(“文件名.rar”)

 

使用drf 方法

from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from django.http import StreamingHttpResponse


class DownloadView(viewsets.GenericViewSet,mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)

    def list(self, request, *args, **kwargs):

        def file_iterator(file, chunk_size=512):
            while True:
                c = file.read(chunk_size)
                if c:
                    yield c
                else:
                    break

        file = open('test.zip', 'rb')
        response = StreamingHttpResponse(file_iterator(file))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(quote('test.zip'))
        return response

你可能感兴趣的:(django)