user3011616
user3011616

Reputation: 21

Get uploaded file name with Google App Engine Request class

I have an HTML form that allows file uploads. I need to send the uploaded file via email. I am following the Google appengine Request class 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 <[email protected]>",
                        subject="Email from me")
          message.to = "Me <[email protected]>"
          message.body = "See attached file."
          message.attachments = [(uploaded_name, uploaded_file)]
          message.send()

The above code works. I need to replace the hardcoded file name (file.doc) in the message.attachments tuple with the actual name of the file uploaded. I have two questions:

  1. How do I get the uploaded file name from the webapp Request class?
  2. Where can I find the documentation that describes how to do this? I have done a bunch of searching and can not find reference material or examples.

UPDATE: Looks like the solution is:

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

...as posted here.

Upvotes: 2

Views: 1090

Answers (1)

Ahmer Kureishi
Ahmer Kureishi

Reputation: 31

Instead of going self.request.get("upload"), try examining the self.request.POST["upload"] dict.

Specifically, self.request.POST['upload'] will return a cgi.FieldStorage instance. The attribute you are looking for is filename. Also of interest would be mimetype - and of course data.

For a complete how-to on handling uploads, take a look at this ancient post over at Nick Johnson's blog.

For an under-the-hood look at how webapp2 request data works, consult this portion of webapp2 docs.

Upvotes: 2

Related Questions