django 大檔案下載
阿新 • • 發佈:2019-01-10
使用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