Uploading a video to google app engine blobstore
Asked Answered
C

3

3

I'm trying to associate a video file to a record with a bunch of properties, but can't seem to allow the user to do everything in one form - name the video, provide description and answer some question, AND upload the file.

Here are the steps I'd like to perform:

  1. User is served with a page containing a form with the following fields: Name, Description, File selector.
  2. The file gets stored as a blob and the id gets recorded together with name and description.

Does anyone have any examples of doing this I could learn from or a tutorial you could point me to? The one from google only shows uploading the file and getting redirected to it.

Thanks and sorry for a newbish question!

Caresa answered 4/8, 2010 at 20:5 Comment(0)
S
3

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/

Supramolecular answered 4/8, 2010 at 20:19 Comment(3)
Thanks! Can you give me a little more context for this (more noob questions) - are you using webapp or django?Caresa
I'm using django-nonrel. Since I'm already used to django that was the easiest way to go about doing this because I didn't have to learn webapp. Also there are some imports and such things missing from the code I pasted, tried to give just the relevant bits :)Supramolecular
Sounds good. Thank you! Since I lack experience, I just wanted to make sure I could reference some extra docs to better understand it.Caresa
N
5

http://demofileuploadgae.appspot.com/ - My demo uploader to the blobstore.

My code for the upload: http://code.google.com/p/gwt-examples/source/browse/trunk/DemoUpload/src/org/gonevertical/upload/#upload/server%3Fstate%3Dclosed

Namtar answered 6/9, 2010 at 16:30 Comment(2)
By the way, to clarify for those looking at these examples, this one is JAVACaresa
well I can upload image file of 3.4 MB using this , I doubt it is following the same source that is linkedGuanajuato
S
3

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/

Supramolecular answered 4/8, 2010 at 20:19 Comment(3)
Thanks! Can you give me a little more context for this (more noob questions) - are you using webapp or django?Caresa
I'm using django-nonrel. Since I'm already used to django that was the easiest way to go about doing this because I didn't have to learn webapp. Also there are some imports and such things missing from the code I pasted, tried to give just the relevant bits :)Supramolecular
Sounds good. Thank you! Since I lack experience, I just wanted to make sure I could reference some extra docs to better understand it.Caresa
F
1

Here is how I did it. It is more straight forward than you think. Note the following taken from Blobstore overview. "When the Blobstore rewrites the user's request, the MIME parts of the uploaded files have their bodies emptied, and the blob key is added as a MIME part header. All other form fields and parts are preserved and passed to the upload handler." In the upload handler is where you can do whatever it is you want with the other form fields.

    class Topic(db.Model):
        title = db.StringProperty(multiline=False)
        blob = blobstore.BlobReferenceProperty()
        imageurl = db.LinkProperty()

    class MainHandler(webapp.RequestHandler):
        def get(self):
            upload_url = blobstore.create_upload_url('/upload')
            self.response.out.write('<html><body>')
            self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
            self.response.out.write("""Upload File: <input type="file" name="file"><br>
            <div><label>Title:</label></div>
            <div><textarea name="title" rows="1" cols="25"></textarea></div><input type="submit" 
                name="submit" value="Submit"> </form>""")
            self.response.out.write('<br><br><h2>TOPIC LIST</h2><table border="1"><tr><td>')
            for topic in Topic.all():                
                self.response.out.write('<div><img src="%s=s48"/>' % topic.imageurl)
                self.response.out.write('<div><b>Image URL: </b><i>%s</i></div>' % topic.imageurl)
                self.response.out.write('<div><b>Title: </b><i>%s</i></div>' % topic.title)
            self.response.out.write('</td></tr></table><br>') 
            self.response.out.write('</body></html>')

    class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
        def post(self):
            upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
            blob_info = upload_files[0]
            topic = Topic()
            topic.title = self.request.get("title")
            topic.blob = blob_info.key()
            topic.imageurl = images.get_serving_url(str(blob_info.key()))
            topic.put()        
            self.redirect('/')
def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
          ], debug=True)
    run_wsgi_app(application)
Franckot answered 12/11, 2010 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.