简体   繁体   English

django下载生成的文件

[英]django download generated file

Download a generated file (.xlsx). 下载生成的文件(.xlsx)。 This is a snippet from a view. 这是一个摘录。 Are better solutions than this? 有更好的解决方案吗?

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

May be you should send the file as a chunk , which is memory efficient 可能是您应该将文件作为块发送,这样可以节省内存

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM