【问题标题】:Google AppEngine Python Web upload file and read the contentGoogle AppEngine Python Web 上传文件并读取内容
【发布时间】:2014-09-24 22:03:30
【问题描述】:

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

所以,我正在使用带有 python 和 HTML 的 Google AppEngine...

所以在我的 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 文件中,类似这样的内容:

类留言簿(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']

但我有一个“文件”的密钥错误。

那么,我怎样才能读取用户直接在浏览器中上传的文件的内容呢?

【问题讨论】:

标签: python html google-app-engine upload


【解决方案1】:

您可以使用 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')

示例取自this gist

【讨论】:

  • 但是如果有多个文件怎么办?对于我field_storage,只包含一个 FieldStorage 实例而不是三个
  • blobstore 支持在单个请求中上传多个文件。
【解决方案2】:

试试这个:

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

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

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

【讨论】:

  • 好的,我将它添加到我的代码中,我不再收到错误,但我看不到如何打印我在 Web 应用程序中上传的 xml 文件的内容。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多