Django 大文件传输
· ☕ 2 分钟
1. 直接返回文件 如果静态文件在工程根目录的 media/test.zip,需要先将文件读入内存,再进行传输。代码如下: settings.py 配置 1 2 PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/') yourapp/views.py 1 2 3 4 5 6 7 8 9 10 11 12 from django.conf import settings from django.http import HttpResponse from django.core.files.storage import FileSystemStorage def download_file_direct_from_file(request): file_system = FileSystemStorage(settings.MEDIA_ROOT) file_name = 'test.zip' with file_system.open(file_name) as f: response = HttpResponse(f) response['Content-Type'] = 'application/%s' % file_name.split('.')[-1] response['Content-Disposition'] = 'attachment; filename="%s"'% file_name return