How to store files inside directory for temporary and make a zip file?

Viewed 40

Here I have a list of images that I want to make a zip and download. For this I tried to upload these images inside the project directory first and then trying to zip from this uploaded files.

I am getting this error:

IOError: [Errno 21] Is a directory: '/home/project/images'

How can I send a zip file with these images ?

images_list = [image_absolute_url1, image_absolute_url2]
folder = os.path.join(BASE_DIR, "images")
os.mkdir(folder)
with open(folder, 'wb+') as f:
    for file in images_list:
        f.write(file)
response = HttpResponse(content_type='application/zip')
zip_file = zipfile.ZipFile(response, 'w')
for filename in images_list:
    zip_file.write(filename)
response['Content-Disposition'] = 'attachment; zip_file'
return response

UPDATE: Thanks to @Michael now the files are created inside directory as 0,1 and inside 0,1 there are images links.

Now I am getting issues with zip

OSError: [Errno 2] No such file or directory: '0'

Updated Code

    for i, imgfile in enumerate(image_list):
        with open(os.path.join(folder, str(i)), 'wb+') as f:
            f.write(imgfile)
    response = HttpResponse(content_type='application/zip')
    zip_file = zipfile.ZipFile(response, 'w')
    folder_files = os.listdir(folder)
    for filename in folder_files:
       file = os.path.join(folder, filename)
       zip_file.write(file)
    response['Content-Disposition'] = 'attachment; zip_file.zip'
    return response

New error response:

AttributeError: 'HttpResponse' object has no attribute 'seek'
1 Answers

You have to open (and automatically create) files in the folder. You can't open and write to the folder (aka directory) itself.

Basically this can look like:

from os.path import join

.
.
.

for i, imgfile in enumerate(images_list):
    with open(join(folder, str(i)), 'wb+') as f:
        f.write(imgfile)

This needs a lot of work yet to avoid e. g. name clashes of filenames if there are already files in the folder.

Related