import zipfile,tarfile
from io import BytesIO
# 创建io对象
s = BytesIO()
fzip = zipfile.ZipFile(s, 'w')
# 遍历要压缩目录
try:
def dfs_search_file_to_zip(input, fzip):
for name in os.listdir(input):
fpath = join(input + "/" + name)
if os.path.isdir(fpath):
dfs_search_file_to_zip(fpath, fzip)
else:
arcname = os.path.relpath(fpath, target_path)
fzip.write(fpath, arcname)
dfs_search_file_to_zip(target_path, fzip)
fzip.close()
data = s.tell()
s.seek(0)
wrapper = FileWrapper(s)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = f'attachment;filename={project_name}.zip'
response['Content-Length'] = data
return response
except Exception as e:
return JsonResponse({"message": e.args})
finally:
# 关闭
s.close()
网友评论