这里我有一个带有url的图像列表。我想创建一个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