How to Zip Mulitiple Files in Python for Download using FastAPI
Python provides zipfile, a built-in module to zip files. Zipping files also help to reduce the size of the files.
ZIP is a file format that compresses data without reducing the quality. The original data can be completely rebuilt from the compressed data.
In this example tutorial, we will show you how to write code for zipping multiple files in Python for download using FastAPI.
Here is a code to zip multiple files in Python:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import uvicorn
import zipfile
from io import BytesIO
app = FastAPI()
@app.get("/files/download/{file_id}")
async def download_image_by_id(file_id: int):
# Get filenames from the database
file_list = ['E:\\files\image_1.jpg', 'E:\\files\image_2.jpg',
'E:\\files\image_3.jpg', 'E:\\files\image_4.jpg',
'E:\\files\image_5.jpg']
return zipfiles(file_list)
def zipfiles(file_list):
io = BytesIO()
zip_sub_dir = "final_archive"
zip_filename = "%s.zip" % zip_sub_dir
with zipfile.ZipFile(io, mode='w', compression=zipfile.ZIP_DEFLATED) as zip:
for fpath in file_list:
zip.write(fpath)
#close zip
zip.close()
return StreamingResponse(
iter([io.getvalue()]),
media_type="application/x-zip-compressed",
headers = { "Content-Disposition":f"attachment;filename=%s" % zip_filename}
)
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8005)
print("running")