繁体   English   中英

Google AppEngine Python Web上传文件并阅读内容

[英]Google AppEngine Python Web upload file and read the content

我是Python和AppEngine的新手,所以也许我的问题是基本的,但我已经搜索了好几个小时......

所以,我正在使用谷歌AppEngine与python和HTML ...

所以在我的htlm文件中我有类似的东西:

 <form action="/sign?guestbook_name={{ guestbook_name }}" method="post">
  <div><input type="file" name="file"></div>
  <div><textarea name="content" rows="3" cols="60"></textarea></div>
  <div><input type="submit" value="Sign Guestbook"></div>
</form>

在我的py文件中,类似的东西:

class Guestbook(webapp2.RequestHandler):

    def post(self):
    # We set the same parent key on the 'Greeting' to ensure each Greeting
    # is in the same entity group. Queries across the single entity group
    # will be consistent. However, the write rate to a single entity group
    # should be limited to ~1/second.
    guestbook_name = self.request.get('guestbook_name',
                                      DEFAULT_GUESTBOOK_NAME)
    greeting = Greeting(parent=guestbook_key(guestbook_name))

    if users.get_current_user():
        greeting.author = users.get_current_user()

    greeting.content = self.request.get('file')


    greeting.put()

    query_params = {'guestbook_name': guestbook_name}
    self.redirect('/?' + urllib.urlencode(query_params))


application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=True)

所以我将感谢信保存到了“greeting.content = self.request.get('file')”数据存储区中文件的名称。

但实际上我想上传我的文件。 打开并阅读python的内容,以便上传它的用户可以在他的浏览器中看到该文件的内容。

我该怎么做 ?

我试着用:

Import cgi
form = cgi.FieldStorage()

# A nested FieldStorage instance holds the file
fileitem = form['file']

但是我的'文件'有一个Key错误。

那么,我如何阅读用户直接在浏览器中上传的文件内容?

您可以使用cgi.FieldStorage()上传<32兆字节的文件。 但您必须将表单发送为enctype="multipart/form-data"

<form action="/upload" enctype="multipart/form-data" method="post">
    <div><input type="file" name="file"/></div>
    <div><input type="submit" value="Upload"></div>
</form>

/upload webapp2请求处理程序中的post方法:

def post(self):

    field_storage = self.request.POST.get("file", None)
    if isinstance(field_storage, cgi.FieldStorage):
        file_name = field_storage.filename
        file_data = field_storage.file.read())
        ..... 

    else:
        logging.error('Upload failed')

这个要点中取出的例子

尝试这个:

fileitem = self.request.POST['file']

如果您想存储该文件,我会先将其直接上传到Blob商店,然后根据需要进行处理。

https://developers.google.com/appengine/docs/python/blobstore/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM