python - 使用 Google App Engine Request 类获取上传的文件名

标签 python class google-app-engine request html-email

我有一个允许文件上传的 HTML 表单。我需要通过电子邮件发送上传的文件。我正在关注 Google appengine Request 类 example .

    from google.appengine.ext import webapp
    from google.appengine.api import mail

    class MyRequestHandler(webapp.RequestHandler):
       def get(self):
          self.response.out.write('''
          <html>
            <body>
              <form method="post">
                <p>File: <input type="file" name="upload" /></p>
                <p><input type="submit" /></p>
              </form>
            </body>
          </html>
          ''')

       def post(self):
          uploaded_file = self.request.get("upload")
          uploaded_name = "file.doc"
          message = mail.EmailMessage(sender="Me <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e030b2e03170a01030f0700400d0103" rel="noreferrer noopener nofollow">[email protected]</a>>",
                        subject="Email from me")
          message.to = "Me <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="462b23062b3f22292b272f286825292b" rel="noreferrer noopener nofollow">[email protected]</a>>"
          message.body = "See attached file."
          message.attachments = [(uploaded_name, uploaded_file)]
          message.send()

上面的代码有效。我需要将 message.attachments 元组中的硬编码文件名 (file.doc) 替换为上传文件的实际名称。我有两个问题:

  1. 如何从 webapp Request 类获取上传的文件名?
  2. 在哪里可以找到描述如何执行此操作的文档?我查了很多资料都没有找到引用资料或例子。

更新: 看起来解决方案是:

 if uploaded_file != "":
    uploaded_name = self.request.params["upload"].filename

...已发布 here .

最佳答案

不要去 self.request.get("upload"),而是尝试检查 self.request.POST["upload"] 字典。

具体来说,self.request.POST['upload'] 将返回一个 cgi.FieldStorage 实例。您要查找的属性是文件名。同样令人感兴趣的是mimetype - 当然还有data

有关处理上传的完整方法,请查看 this ancient post在尼克·约翰逊的博客上。

要深入了解 webapp2 请求数据的工作原理,请参阅 this portion webapp2 文档。

关于python - 使用 Google App Engine Request 类获取上传的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20088154/

相关文章:

python - v # 无效表达式\nsre_constants.error : bad character range , Ansible

python - django-mptt 树重建错误

java - 示例项目 “hello-world” 项目在尝试在 App Engine 上运行时显示错误

java - Google App Engine Java与cassandra修改线程组错误

python - GoogleAppEngine 上的 Django : performance howto

Python 请求库 HTTPBasicAuth 三个参数

python - 在 python 中打印前馈循环

javascript - 根据图像比例添加CSS类

python - 如何引用没有定义变量的现有类对象?

css - 根据类 "range"分配CSS属性