django提供二进制流数据文件的下载

基于djnago框架的二进制流数据传输(提供较大文件的下载)

  (1)数据源:

    高质量图片、视频、音频、文件、数据库数据等。如果是数据库文件,需要先读取相应的数据,然后写入表格在传输到前端以供下载!

  (2)数据读取:

    利用yield函数生成器进行rb模式文件读取操作

  (3)数据传输:

    通过StreamingHttpResponse()二进制流格式进行相应(from django.http.response import StreamingHttpResponse或者使用文件响应FileResponse)

  如果除数中使用的有中文,需要通过quote()方法来确保中文不乱码(from urllib.parse import quote)

文件的上传见<Django之AJAX文件上传>篇,python操作excel表格见<python操作excel----openpyxl模块>或<xpython操作excel之xlwt与xlrd>

接口模式提供唯一码的下载案例  

 1 import os
 2 import openpyxl
 3 from django.views import View
 4 from django.http.response import StreamingHttpResponse
 5 from urllib.parse import quote
 6 
 7 
 8 class FileDownload(View):
 9     def get(self, request, pk=None):
10         #查询书库获相应字段数据
11         queryset = models.Surveys.objects.filter(pk=pk).only('unique_code')#only只显示指定的字段
12 
13         #创建excel写入数据
14         book=openpyxl.Workbook()
15         table=book.create_sheet("唯一码")
16         table.cell(1,1,"唯一码")#openpyxl模块创建的表索引都是从1开始
17         for index, code in enumerate(queryset.iterator(), 2):#查询集合调用iterator方法成迭代器
18             table.cell(index, 1, code.unique_code)
19         book.save("唯一码.xls")
20 
21 
22         #利用生成器进行文件读取
23         def iter_file(path):
24             size=1024
25             with open(path, "rb")as f:
26                 for data in iter(lambda :f.read(size), b''):
27                     yield data
28 
29         #以二进制形式进行数据流传输
30         response=StreamingHttpResponse(iter_file(os.path.join("唯一码.xls")))#以二进制形式响应数据流
31         response['Content-Type'] = 'application/octet-stream'#浏览器不识别的也会自动下载
32         response['Content-Disposition'] = 'attachment; {}'.format(
33             "filename*=utf-8''{}".format(quote("唯一码.xls"))#quote确保中文格式不乱码
34         )
35         return response

   

posted @ 2019-08-19 17:42  笑得好美  阅读(2588)  评论(0编辑  收藏  举报