在django中有多种方式可以让前端下载一个文件,比如excel的文件。这里记录下几种实现的方式。
一. 直接在django项目中有一个现成的excel文件且其中内容都有
1.使用django中的HttpResponse类
(1).使用open()打开二进制方式
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
标签:file,几种,io,HttpResponse,django,response,下载,name From: https://www.cnblogs.com/shaoyishi/p/17806104.html