使用 Django 从服务器获取多个图像
我正在尝试从服务器下载多个图像文件.我在后端使用 Django.与单张图片相关的问题已经回答,我尝试了代码,它适用于单张图片.在我的应用程序中,我想在单个 HTTP 连接中下载多个图像.
I am trying to download multiple image files from the server. I am using Django for my backend. Question related to single image has already been answered and I tried the code and it works on single image. In my application, I want to download multiple images in a single HTTP connection.
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
.我想的一种方法是压缩两个图像并根据客户端大小解压缩它,但我认为这不是一个好的解决方案.有没有办法解决这个问题?
How can I fetch both img
and img2
at once. One way I was thinking is to zip both images and unzip it on client size but I dont think that is good solution. Is there a way to handle this?
我环顾四周,找到了使用磁盘上的临时 Zip 文件的旧解决方案:https://djangosnippets.org/snippets/365/
I looked around and find an older solution using a temporary Zip file on disk: https://djangosnippets.org/snippets/365/
它需要一些更新,这应该可以工作(在 django 2.0 上测试)
It needed some updating, and this should work (tested on 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 次,然后发送.
Right now, this takes my .png and writes it 10 times in my .zip, then sends it.