Uploading a video to google app engine blobstore

最后都变了- 提交于 2020-01-01 06:26:13

问题


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!


回答1:


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/




回答2:


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




回答3:


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)


来源:https://stackoverflow.com/questions/3409375/uploading-a-video-to-google-app-engine-blobstore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!