python - 使用 Django 从服务器获取多个图像

标签 python django web

我正在尝试从服务器下载多个图像文件。我的后端使用 Django。 单图相关问题已经answered我尝试了代码,它适用于单个图像。在我的应用程序中,我想在单个 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

如何同时获取 imgimg2。我想的一种方法是压缩两个图像并将其解压缩到客户端大小,但我认为这不是好的解决方案。有办法处理吗?

最佳答案

我环顾四周,找到了一个使用磁盘上临时 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 次,然后发送。

关于python - 使用 Django 从服务器获取多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027868/

相关文章:

python - django:无法将模型导入到与模型相同路径上的.py

django - sqlite 是否捆绑到 Django 中?

python - Django 1.7 中不再支持数字键选择吗?

html - 如何制作适合所有屏幕分辨率的网页

html - 如何在 body 元素中获得全宽

python - 如何存储上一帧的中心点列表以比较当前帧的中心点列表

python - 如何查看一段时间内收到的所有邮件?

python - 为什么 python.org OS X 安装程序是用 gcc-4.0 构建的?

python - 字符串中所有唯一字符的列表?

PHP-MYSQL脚本无法连接服务器上的数据库