django-下载excel模板文件


后端代码如下:
1 from django.http import StreamingHttpResponse 2 3 def file_down(request): 4 """下载模板的视图""" 5 file_name = "device_template.xlsx" # 文件名 6 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录 7 file_path = os.path.join(base_dir, 'upload', 'export_template', file_name) # 下载文件的绝对路径 8 9 def file_iterator(file_path, chunk_size=512): 10 """ 11 文件生成器,防止文件过大,导致内存溢出 12 :param file_path: 文件绝对路径 13 :param chunk_size: 块大小 14 :return: 生成器 15 """ 16 with open(file_path, mode='rb') as f: 17 while True: 18 c = f.read(chunk_size) 19 if c: 20 yield c 21 else: 22 break 23 24 # 设置响应头 25 # StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法 26 response = StreamingHttpResponse(file_iterator(file_path)) 27 # 以流的形式下载文件,这样可以实现任意格式的文件下载 28 response['Content-Type'] = 'application/octet-stream' 29 # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名 30 response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name) 31 return response
参考文章:https://blog.csdn.net/u014686399/article/details/78198306
posted on 2021-09-25 16:29 cherry_ning 阅读(546) 评论(0) 收藏 举报
浙公网安备 33010602011771号