使用Google App Engine在python中上传文件和表单数据

时间:2013-06-19 21:48:11

标签: python forms google-app-engine

我有一个简单的网络应用程序,用户可以在其中提交表单,并在GAE上托管要包含的文件(如果需要)。我已经看过很多关于如何使用blobstore将文件上传到GAE的教程,它们看起来很简单,比如Upload files in Google App Engine

但是,我如何上传标准表单数据?我有一堆文本框,我希望用户能够提交附件以及输入的文本数据。我只能找到只上传文件的例子。

这是我的HTML表单:

<form action="http://xxx.appspot.com" target="myiframe" method="post" id="myForm" name="myForm">Contact Name<br />
<input type="text" required="" name="cname" /><br />
Name of Institution<br />
<input type="text" required="" name="iname" /><br />
E-Mail<br />
<input type="email" required="" name="email" /><br />
Phone<br />
<input type="tel" required="" name="phone" /><br />
If you have a supporting file that will clarify your help request you can add it here (optional)<br />
<input type="file" name="upfile" MAXLENGTH=50 ALLOW="text/html/text/plain" /><br />
Description of problem/issue<br />
<textarea required="" name="desc" rows="3" cols="30">
</textarea>
<br />
<input type="submit" value="Submit" />
<div id="result"></div>
</form>
<iframe name="myiframe" style="visibility:hidden;display:none" src="http://xxx.appspot.com" id="myiframe"></iframe>

这是我的服务器端python代码。我正在尝试让用户上传文件,然后发送一封包含附件和用户输入数据的电子邮件:

import cgi, cgitb
from google.appengine.api import mail

class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, webapp2 World!')

    def post(self):

        contact=self.request.POST["cname"]
        institute=self.request.POST["iname"]
        email=self.request.POST["email"]
        phone=self.request.POST["phone"]
        desc=self.request.POST["desc"]
        filename=self.request.POST["upfile"]
        user_address = "xxx@xxx.net"

        sender_address = "xxx@gmail.com"
        subject = "Test email"

        body = "Contact Name: "+contact+"\n"+"Name of Institution: "+institute+"\n"+"E-mail: "+email+"\n"+"Phone: "+phone+"\n"+"Description: "+desc#+"\n"+"Filename: "+filename
        mail.send_mail(sender_address, user_address, subject, body)

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

1 个答案:

答案 0 :(得分:0)

不要忘记表单中的enctype:

enctype="multipart/form-data"