【问题标题】:Uploading a file and form data in python with Google App Engine使用 Google App Engine 在 python 中上传文件和表单数据
【发布时间】:2013-06-20 05:58:15
【问题描述】:

我有一个简单的 Web 应用程序,用户可以在其中提交表单,并在需要时包含要上传的文件,托管在 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)

【问题讨论】:

  • 当您使用该代码时会发生什么?
  • 当我取消注释变量文件名时,我得到了实际的文件名。但这只是名字吗?我如何将其附加到电子邮件中?我的做法似乎与 GAE 关于电子邮件附件的文档不太一样(但话又说回来,它们也没有包含相关的 html)。

标签: python forms google-app-engine


【解决方案1】:

不要忘记表单中的 enctype:

enctype="multipart/form-data"

【讨论】:

  • 当我包含它时,我得到 TypeError: coercing to Unicode: need string or buffer, instance found In my GAE logs.
  • 也许这会有所帮助:enctype="multipart/form-data;charset=UTF-8"
  • 我将如何将该文件附加到电子邮件中?我不知道该怎么做。
  • 这是一个不同的问题。在 Google 上搜索或在 SO 上开始另一个问题。
猜你喜欢
  • 1970-01-01
  • 2010-09-10
  • 2013-08-25
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
相关资源
最近更新 更多