使用 Django 从服务器获取多个图像 [英] Fetch multiple images from the server using Django

查看:39
本文介绍了使用 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

如何同时获取 imgimg2.我想的一种方法是压缩两个图像并根据客户端大小解压缩它,但我认为这不是一个好的解决方案.有没有办法解决这个问题?

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.

这篇关于使用 Django 从服务器获取多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆