Google AppEngine Python 网站上传文件并读取内容

1 投票
2 回答
927 浏览
提问于 2025-04-18 15:40

我刚接触Python和AppEngine,所以可能我的问题比较基础,但我搜索了好几个小时也没找到答案……

我正在使用Google AppEngine,结合Python和HTML……

在我的HTML文件里,有这样的内容:

 <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>

而在我的Python文件里,有这样的内容:

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']

但是我遇到了一个关于'file'的键错误。

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

2 个回答

0

试试这个:

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

如果你想保存文件,我建议你先把它直接上传到Blob存储,然后再根据需要进行处理。

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

2

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

这个例子来自于 这个链接

撰写回答