Here's the code I'm using to upload images and associate them with articles. The toughest bit was getting the article id to get to the upload handler, I solved it by setting the file name as the article id to get around the problem.
from lib import urllib2_file
from lib.urllib2_file import UploadFile
# this view serves a task in a queue
def article(request):
article = Article.objects.get(id=form.cleaned_data['article'])
try:
image = StringIO(urllib2.urlopen(image_url).read())
except (urllib2.HTTPError, DownloadError):
article.parsed = True
article.save()
else:
image = UploadFile(image, '.'.join([str(article.id), image_url.rsplit('.', 1)[1][:4]]))
upload_url = blobstore.create_upload_url(reverse('Articles.views.upload'))
try:
urllib2.urlopen(upload_url, {'file': image})
except (DownloadError, RequestTooLargeError):
pass
return HttpResponse(json.dumps({'status': 'OK'}))
def upload(request):
if request.method == 'POST':
blobs = get_uploads(request, field_name='file', populate_post=True)
article = Article.objects.get(id=int(blobs[0].filename.split('.')[0]))
article.media = blobs[0].filename
article.parsed = True
article.save()
return HttpResponseRedirect(reverse('Articles.views.upload'))
else:
return HttpResponse('meow')
def upload(request):
if request.method == 'POST':
blobs = get_uploads(request, field_name='file', populate_post=True)
article = Article.objects.get(id=int(blobs[0].filename.split('.')[0]))
article.media = blobs[0].filename
article.parsed = True
article.save()
return HttpResponseRedirect(reverse('Articles.views.upload'))
else:
return HttpResponse('meow')
# this serves the image
def image(request):
blob = BlobInfo.gql("WHERE filename='%s' LIMIT 1" % request.form.cleaned_data['id'])[0]
return HttpResponse(BlobReader(blob.key()).read(),
content_type=blob.content_type)
Also you'll need this http://fabien.seisen.org/python/urllib2_file/