代码实现
# 创建一个目录来保存这些东西
temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4()))
os.makedirs(temp_path)
# 创建压缩文件
archive_path = os.path.join(temp_path, 'archive.zip')
with zipfile.ZipFile(archive_path, 'w') as zf:
# 把图片添加到压缩文件中
zf.write(image_path, arcname=f'{photo.pk}.png')
zf.write(image_path, arcname=f'{photo.pk}.png')
zf.write(image_path, arcname=f'{photo.pk}.png')
zf.write(image_path, arcname=f'{photo.pk}.png')
# 返回压缩文件地址,下载
return HttpResponseRedirect(f'{settings.MEDIA_URL}temp/{os.path.basename(temp_path)}/archive.zip')
参考资料
- 官方文档:https://docs.python.org/zh-cn/3/library/zipfile.html
- 用 Python 压缩文件方法汇总:https://qiwsir.github.io/2021/09/15/compressandarchivefile/
- How to Create and Serve Zipfiles from Django:https://pybit.es/articles/django-zipfiles/