A few weeks ago we launched a Facebook application that would zip up all the pictures a user was tagged in on Facebook. Alana Taylor had come up with he idea, and over a weekend a group of us pumped out the application. Since the application was built with Google App Engine, I thought it would be useful for others to know how to take multiple images across the web and zip them up into one file.

Start by Importing the following:

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
import zipfile

The code is simple, I won't go through each line of code since its self explanatory. The process uses a StringIO object to store the Zip file.

def addFile(self,zipstream,url,fname):
    # get the contents		
    result = urlfetch.fetch(url)

    # store the contents in a stream
    f=StringIO(result.content)
    length = result.headers['Content-Length']
    f.seek(0)
                
    # write the contents to the zip file
    while True:
	buff = f.read(int(length))
	if buff=="":break
	zipstream.writestr(fname,buff)
    return zipstream

def ZipFiles(self):
    # create the zip stream
    zipstream=StringIO()
    file = zipfile.ZipFile(zipstream,"w")
		
    url = 'http://someplace.tld/outimage.jpg'

    # repeat this for every URL that should be added to the zipfile
    file =self.addFile(file,url,"ourimage.jpg")
                
    # we have finished with the zip so package it up and write the directory
    file.close()
    zipstream.seek(0)

    # create and return the output stream
    self.response.headers['Content-Type'] ='application/zip'
    self.response.headers['Content-Disposition'] = 'attachment; filename="outfile.zip"'	
    while True:
	buf=zipf.read(2048)
	if buf=="": break
	self.response.out.write(buf)

Remember you can not send more than 1 MB in data with GAE. This means all zip files must be smaller than 1MB.