Django响应大文件下载请求

来源:互联网 发布:数据库存储图片 编辑:程序博客网 时间:2024/05/17 02:40

Django响应大文件下载请求

简单记录下过程和代码:
1、压缩成zip文件;
2、分块读取zip文件并返回

import osimport zipfilefrom django.http import StreamingHttpResponsedef send_zipfile(path, suggestName):    def file_iterator(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    def zipfolder(path, zipfileName):        tmp = os.path.join(path, zipfileName)        archive = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED)        for d in os.listdir(path):            fp = os.path.join(path, d)            if fp != tmp and os.path.isfile(fp):                archive.write(fp, d)        archive.close()        return tmp    the_file_name = zipfolder(path, '%s.zip' % suggestName)    response = StreamingHttpResponse(file_iterator(the_file_name))    response['Content-Type'] = 'application/zip'    response['Content-Disposition'] = 'attachment;filename="%s.zip"' % suggestName    return response
0 0