django后端给前端返回下载文件
组织响应from django.http import StreamingHttpResponsedef read_file(file_name, chunk_size=512):with open(file_name, "rb") as f:while True:c = f.read(chunk_size)if c:yield celse:
·
第一种直接读取文件返回响应
from django.http import StreamingHttpResponse
def read_file(file_name, chunk_size=512):
with open(file_name, "rb") as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
def test(request):
file_path = ""
file_name = ""
response = StreamingHttpResponse(read_file(file_path))
response["Content-Type"] = "application/octet-stream"
response["Content-Disposition"] = 'attachment; filename={0}'.format(file_name)
response["Access-Control-Expose-Headers"] = "Content-Disposition" # 为了使前端获取到Content-Disposition属性
return response
第二种生成文件的时候返回,比如excel或者docx,这样不需要本地生成文件
sio = BytesIO()
doc.save(sio) # word文档生成对象保存
# wb.save(sio) # 或者excel生成的对象保存
sio.seek(0)
response = HttpResponse(content_type="application/octet-stream")
response["Content-Disposition"] = 'attachment; filename={0}'.format(file_name)
response["Access-Control-Expose-Headers"] = "Content-Disposition" # 为了使前端获取到Content-Disposition属性
response["Access-Control-Expose-Headers"] = "Content-Disposition"
response.write(sio.getvalue())
return response
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)