[英]How to create and download a zip file with a list of images?
在这里,我有图片列表及其网址。 我想创建一个 zip 并将所有图像存储在 zip 中。 提取 zip 文件后,我想要文件夹内的图像。
下面的代码发生了什么:
它会创建 zip 和下载,但是当我提取 zip 文件时,有很多文件夹,如zipfoldername/home/user/my_project/img
并且只有在 img 文件夹中才有文件。 我想要的只是zipfoldername/img
。
此外,在img
文件夹文件中没有图像,它只有 image_url。 我想将该图像 url 中的图像存储在提取的文件中。
image_list = ['https://example.com/media/file1.jpg', 'https://example.com/media/file2.jpg']
folder = os.path.join(settings.BASE_DIR, "imgs")
if not os.path.exists(folder):
os.mkdir(folder)
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')
s = StringIO.StringIO()
zip_file = zipfile.ZipFile(s, "w")
folder_files = os.listdir(folder)
for filename in folder_files:
file = os.path.join(folder, filename)
zip_file.write(file)
zip_file.close()
resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed")
resp['Content-Disposition'] = 'attachment; filename=gik.zip'
return resp
使用os
获取文件名并使用writestr
将下载文件的字节写入 zipfile
import os
import zipfile
import requests
images = [
"https://via.placeholder.com/350x150.jpg",
"https://via.placeholder.com/350x250.jpg",
]
with zipfile.ZipFile('someZipFile.zip', 'w') as img_zip:
for image_url in images:
img_name = os.path.basename(image_url)
img_data = requests.get(image_url).content
img_zip.writestr(img_name, img_data)
如果你想在 zip 文件夹中创建一个名为img
的文件夹,你可以更改:
img_zip.writestr(img_name, img_data)
至
img_zip.writestr(f"img/{img_name}", img_data)
如果您在 HTTP 响应中返回存档,您可以将其保存到缓冲区,然后用缓冲区响应
buffer = io.BytesIO()
with zipfile.ZipFile(buffer , 'w') as img_zip:
...
response = HttpResponse(buffer.getvalue())
response['Content-Type'] = 'application/x-zip-compressed'
response['Content-Disposition'] = 'attachment; filename=file.zip'
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.