django后端给前端返回下载文件

第一种直接读取文件返回响应

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

你可能感兴趣的:(django)