Search code examples
pythonpython-3.xdjangodjango-4.0

How to create a zip with multiple files from one folder and send it to the browser in modern Django


I was struggling with sending the downloadable Django zip with many files to browser, because many tutorials in the web are obsolete, like the one which was my inspiration to come up with what I will share with you:

Django - Create A Zip of Multiple Files and Make It Downloadable


Solution

  • THE SOLUTION

    We're not using many functions in this projects but rather blocks of code with docstrings, but you can easily pack this code into a function:

    from io import BytesIO
    from zipfile import ZipFile
    
    from django.http import HttpResponse
    
    #get the name of the folder you want to download from the frontend using input
    directory_name = request.POST["folder"]
    
    #create the zip file
    file_blueprint = BytesIO()
    zip_file = ZipFile(file_blueprint, 'a')
    
    #create the full path to the folder you want to download the files from
    directory_path = BASE_PATH + directory_name
    
    for filename in os.listdir(directory_path):
        try:
        #characterize the from path and the destination path as first and second argument
            zip_file.write(os.path.join(directory_path + "/" + filename), os.path.join(directory_name + "/" + filename))
        except Exception as e:
            print(e)
    zip_file.close()
    
    #define the the zip file as a response
    response = HttpResponse(file_blueprint.getvalue(), content_type = "application/x-zip-compressed")
    response["Content-Disposition"] = "attachment; filename= your-zip-folder-name.zip"
    
    return response