python - 使用 Django 从服务器获取多张图片
问题描述
我正在尝试从服务器下载多个图像文件。我正在使用 Django 作为我的后端。与单个图像相关的问题已经得到解答,我尝试了代码,它适用于单个图像。在我的应用程序中,我想在单个 HTTP 连接中下载多个图像。
from PIL import Image
img = Image.open('test.jpg')
img2 = Image.open('test2.png')
response = HttpResponse(content_type = 'image/jpeg')
response2 = HttpResponse(content_type = 'image/png')
img.save(response, 'JPEG')
img2.save(response2, 'PNG')
return response #SINGLE
我怎样才能同时获取img
两者img2
。我想的一种方法是压缩两个图像并将其解压缩到客户端大小,但我认为这不是一个好的解决方案。有没有办法处理这个?
解决方案
我环顾四周,使用磁盘上的临时 Zip 文件找到了一个较旧的解决方案:https ://djangosnippets.org/snippets/365/
它需要一些更新,这应该可以工作(在 django 2.0 上测试)
import tempfile, zipfile
from django.http import HttpResponse
from wsgiref.util import FileWrapper
def send_zipfile(request):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.
"""
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for index in range(10):
filename = 'C:/Users/alex1/Desktop/temp.png' # Replace by your files here.
archive.write(filename, 'file%d.png' % index) # 'file%d.png' will be the
# name of the file in the
# zip
archive.close()
temp.seek(0)
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test.zip'
return response
现在,这需要我的 .png 并在我的 .zip 中写入 10 次,然后发送它。