【问题标题】:Fetch multiple images from the server using Django使用 Django 从服务器获取多张图片
【发布时间】:2018-12-04 06:55:35
【问题描述】:

我正在尝试从服务器下载多个图像文件。我正在使用 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

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

【问题讨论】:

  • 如果你使用 for 循环遍历图片所在的目录会怎样?

标签: python django web


【解决方案1】:

您可以将文件/图像添加到 ZIP 文件并在响应中返回该文件。我认为这是最好的方法。

以下是一些示例代码,说明如何实现这一目标(来自 this post):

def zipFiles(files):
    outfile = StringIO() # io.BytesIO() for python 3
    with zipfile.ZipFile(outfile, 'w') as zf:
        for n, f in enumarate(files):
            zf.writestr("{}.csv".format(n), f.getvalue())
    return outfile.getvalue()

zipped_file = zip_files(myfiles)
response = HttpResponse(zipped_file, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=my_file.zip'

否则(如果您不喜欢 ZIP 文件)您可以从客户端发出单独的请求。

【讨论】:

    【解决方案2】:

    我环顾四周,发现使用磁盘上的临时 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 次,然后发送它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 2019-03-07
      • 2014-05-31
      • 2013-01-12
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多