user1283941
user1283941

Reputation: 35

Downloading images from url in memory and creating zip archive in memory to send to the browser

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

Upvotes: 2

Views: 4041

Answers (2)

John
John

Reputation: 5206

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

Upvotes: 3

Mihnea Simian
Mihnea Simian

Reputation: 1103

You can do that, simply:

response = urllib2.urlopen('http://..')
img_bytes = response.read()

and then use ZipFile.writestr to write these bytes into a file, inside the Zip you previously created passing a StringIO handler instead of a real file handler. When finished writing files, return this as HTTPResponse setting proper mimetype and content disposition.

But I wouldn't use the RAM for this. Why not use tempfile.NamedTemporaryFile?

Upvotes: 0

Related Questions