我正在使用multipart / form / data上传一个xml文件,需要读取xml文件内容并在response.write()中打印xml文件内容
MAIN_PAGE_HTML = """\
<html>
<body>
<form action="/f1" method="post" enctype="multipart/form-data">
<div><input type="file" name="filecoll"></div>
<div><input type="submit" value="Submit "></div>
</form>
</body>
</html>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(MAIN_PAGE_HTML)
class formfiless(webapp2.RequestHandler):
def post(self):
self.response.write('<html><body>You wrote:<pre>')
self.response.write(cgi.escape(self.request.get('filecoll')))
f=self.request.get('filecoll')
data=f.read()
self.response.write('</pre></body></html>')
application = webapp2.WSGIApplication([
('/',MainPage),
('/f1',formfiless),
], debug=True)
当我尝试读取表单文件时发生以下错误。
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\uniphoreC08\Desktop\upload_grammar\helloworld.py", line 35, in post
f.read()
AttributeError: 'unicode' object has no attribute 'read'
答案 0 :(得分:0)
电话
self.request.get('filecoll')
似乎产生了一个unicode字符串,而不是一个文件对象。在下一行中,您将调用read()方法,就好像它是一个文件对象一样。因此
AttributeError:&#39; unicode&#39;对象没有属性&#39;读&#39;
答案 1 :(得分:0)
以下是将xml文件作为字符串写入网络的示例代码。
class MPost(webapp2.RequestHandler):
def post(self):
uploaded_file = self.request.body
self.response.headers['Content-Type'] = 'text/plain'
self.response.write(str(uploaded_file))
而不是请求争论,使用请求体和body_file:body是主体内容作为字节字符串,body_file为相同的数据提供类似文件的接口: