django中几种下载文件的方法
在django中有多种方式可以让前端下载一个文件,比如excel的文件。这里记录下几种实现的方式。
一. 直接在django项目中有一个现成的excel文件且其中内容都有
1.使用django中的HttpResponse类
(1).使用open()打开二进制方式
1 2 3 4 5 6 7 8 9 | from django.http import HttpResponse path = "a.xlsx" f = open (path, "rb" ) response = HttpResponse(content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response[ 'Content-Disposition' ] = f 'attachment; filename="{escape_uri_path(self.__template_name)}"' response[ 'Access-Control-Expose-Headers' ] = 'content-disposition' response.write(f.read()) f.close() return response |
(2). 使用io.BytesIO()
import io from django.http import HttpResponse path = "a.xlsx" f =open(path,"rb") response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename="{escape_uri_path(self.__template_name)}"' response['Access-Control-Expose-Headers'] = 'content-disposition' io_obj = io.BytesIO(f.read()) response.write(io_obj.getvalue()) f.close() return respons
注意:使用io.BytesIO效率会更高。
2.使用django中的FileResponse类
from django.http import FileResponse f = open(path_, 'rb') response = FileResponse(f) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment; filename="%s"' % (urlquote(filename)) response['Access-Control-Expose-Headers'] = 'content-disposition' f.close() return response
3.使用django中的StreamingHttpResponse类
def file_iterator(file_name, chunk_size=512): with open(file_name) as f: while True: c = f.read(chunk_size) if c: yield c else: break the_file_name = "big_file.pdf" response = StreamingHttpResponse(file_iterator(the_file_name)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name) return response
二. 在django项目中没有现成的excel
这里只举例使用openpyxl来创建excel。
from django.http import HttpResponse import io from openpyxl import Workbook # 创建一个工作簿并向其中添加一些数据 workbook = Workbook() sheet = workbook.active sheet['A1'] = 'Hello' sheet['B1'] = 'World' # 将工作簿保存到 BytesIO 对象 buffer = io.BytesIO() workbook.save(buffer) # 将文件指针重置到开头 buffer.seek(0) # 创建 HTTP 响应 response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="example.xlsx"' # 将 BytesIO 对象中的数据作为响应内容发送 response.write(buffer.getvalue()) # 返回响应 return response
当然,上述中的HttpResponse也可以是FileResponse, StreamingHttpResponse
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2022-11-02 Django当中如何实现用xlwt来导出一个excel文件?