从内存中的url下载图像,并在内存中创建zip存档以发送到浏览器 [英] Downloading images from url in memory and creating zip archive in memory to send to the browser

查看:177
本文介绍了从内存中的url下载图像,并在内存中创建zip存档以发送到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django项目中,我需要发送zip文件到客户端进行下载。这个zip文件将包含从各种URL下载的图像。



是否可能将内存中的图像下载到内存中,然后将其添加到内存中的zip文件中,再次将zip文件写入磁盘,最后将该zip文件发送到客户端进行下载?



我知道urllib2可以用于图像下载和zip文件,用于处理zip文件,但面临在内存中执行这些操作的问题。所以这方面的一些例子是非常感激的。 / p>

谢谢

解决方案

使用urllib2下载文件。打开一个新的ZipFile进行写入(您将需要一个StringIO对象)。将url的输出写入ZilpFile.writestr。将zip文件附加到django响应。

  import urllib2 
from StringIO import StringIO

url = urllib2.urlopen('http://example.com/foo.jpg')
f = StringIO()
zip = zipfile.ZipFile(f,'w')
zip.writestr ('foo.jpg',url.read())
response = HttpResponse(f.getvalue(),content_type =application / zip)
response ['Content-Disposition'] ='attachment ; filename = foobar.zip'
return response


In my django project i need to send a zip file to the client side for download.This zip file would contain images downloaded from various url's.

Is it possible to download the images in memory without writing the image files to disk then add them to a zip file in memory itself,again not writing the zip file to disk and finally sending the zip file to the client for download ?

Im aware that urllib2 can be used for image downloads and zipfile for working with zip files but facing a problem with performing these operations in memory itself.So,some example for this would be really appreciated.

Thank You

解决方案

Download the file with urllib2. Open a new ZipFile for writing (you'll need a StringIO object for this). Write the output from the url into ZilpFile.writestr. Attach zip file to django response.

import urllib2
from StringIO import StringIO

url = urllib2.urlopen('http://example.com/foo.jpg')
f = StringIO()
zip = zipfile.ZipFile(f, 'w')
zip.writestr('foo.jpg', url.read())
response = HttpResponse(f.getvalue(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=foobar.zip'
return response

这篇关于从内存中的url下载图像,并在内存中创建zip存档以发送到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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