django 下载生成的文件
django download generated file
下载生成的文件 (.xlsx)。这是一个视图的片段。
有比这更好的解决方案吗?
inventory_file = open(file_path, "rb")
response = HttpResponse(inventory_file, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
也许你应该将文件作为一个块发送,这样内存效率更高
import os
import mimetypes
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
def download_file(request):
the_file = open(file_path, "rb")
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
下载生成的文件 (.xlsx)。这是一个视图的片段。 有比这更好的解决方案吗?
inventory_file = open(file_path, "rb")
response = HttpResponse(inventory_file, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
也许你应该将文件作为一个块发送,这样内存效率更高
import os
import mimetypes
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
def download_file(request):
the_file = open(file_path, "rb")
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