django返回文件(无论什么格式的)给前端

读取文件方法:

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
View Code

 

from django.http import StreamingHttpResponse
from django.utils.encoding import escape_uri_path
file_name = f"{platform_cn}成本数据.xlsx"
response = StreamingHttpResponse(read_file(file_path))
response["Content-Type"] = "application/octet-stream" # 这里就写这个就可以,如果错了你去看中文乱码就会格式不对
response["Content-Disposition"] = f"'attachment; filename={escape_uri_path(file_name)}" # 文件名称是中文,防止中文乱码
response["Access-Control-Expose-Headers"] = "Content-Disposition" # 为了使前端获取到Content-Disposition属性

 

再给你们带一张图吧

 

posted @ 2023-03-16 19:11    阅读(283)  评论(0编辑  收藏  举报