Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Jazzis18/28a959471c2c50bf0b680e3da36d247c to your computer and use it in GitHub Desktop.
Save Jazzis18/28a959471c2c50bf0b680e3da36d247c to your computer and use it in GitHub Desktop.
A simple snippet to zip files in a directory and send it the browser in downloadable format in django
from shutil import make_archive
from wsgiref.util import FileWrapper
def download(request, file_name=""):
"""
A django view to zip files in directory and send it as downloadable response to the browser.
Args:
@request: Django request object
@file_name: Name of the directory to be zipped
Returns:
A downloadable Http response
"""
files_path = "/tmp/albums/"
path_to_zip = make_archive(files_path, "zip", files_path)
response = HttpResponse(FileWrapper(open(path_to_zip,'rb')), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="{filename}.zip"'.format(
filename = file_name.replace(" ", "_")
)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment