我是 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>
在我的 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']
但是我遇到了"file"的关键错误。
那么,如何在浏览器中直接读取用户上传的文件内容呢?
最佳答案
您可以使用 cgi.FieldStorage() 上传 < 32 MB 的文件。但您必须将表单发送为 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
关于python - Google AppEngine Python Web上传文件并读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084667/