在 Google App Engine 中上传文件
我计划创建一个 Web 应用程序,允许用户降级他们的 Visual Studio 项目文件.但是,Google App Engine 似乎通过 db.TextProperty
和 db.BlobProperty
接受文件上传和平面文件存储在 Google 服务器上.
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through db.TextProperty
and db.BlobProperty
.
我很高兴任何人都可以提供代码示例(客户端和服务器端)来说明如何做到这一点.
I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
这是一个完整的工作文件.我从 Google 网站上提取了原件并对其进行了修改,使其更加真实.
Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.
需要注意的几点:
- 此代码使用 BlobStore API
这一行在ServeHandler 类是为了修复"键,以便它摆脱任何名称可能发生在浏览器(我没有观察到任何铬)
- This code uses the BlobStore API
The purpose of this line in the ServeHandler class is to "fix" the key so that it gets rid of any name mangling that may have occurred in the browser (I didn't observe any in Chrome)
blob_key = str(urllib.unquote(blob_key))
末尾的save_as"子句很重要.它将确保文件名在发送到您的浏览器时不会被破坏.摆脱它以观察会发生什么.
The "save_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens.
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
祝你好运!
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
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> <input type="submit" name="submit" value="Submit"> </form></body></html>""")
for b in blobstore.BlobInfo.all():
self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/')
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
blob_key = str(urllib.unquote(blob_key))
if not blobstore.get(blob_key):
self.error(404)
else:
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()