Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle uploaded files in webapp2

Google appengine's webapp2 has a very cryptic documentation regarding the handling of uploaded files.

Uploaded files are available as cgi.FieldStorage (see the cgi module) instances directly in request.POST.

I have a form which makes a POST request of JSON files which I want to store in an NDB.JsonProperty.

Can anyone offer a short example of how do I read the file from the request object?

like image 411
fccoelho Avatar asked Nov 27 '12 13:11

fccoelho


2 Answers

You can use enctype="multipart/form-data" in your form, and then get file content by using in your handler:

raw_file = self.request.get('field_name')

Then, pass raw_file as input to your model's property.

like image 122
Thanos Makris Avatar answered Oct 03 '22 07:10

Thanos Makris


Google's document just sucks. I've spent about two hours experimenting with webapp2's request object and finally figures out a way to do this.

Check https://stackoverflow.com/a/30969728/2310396.

The basic code snippets is here:

class UploadHandler(BaseHandler):
    def post(self):
        attachments = self.request.POST.getall('attachments')

        _attachments = [{'content': f.file.read(),
                         'filename': f.filename} for f in attachments]

We use self.request.POST.getall('attachments') instead of self.request.POST.get('attachments'), since they may be multiple input field in HTML forms with the same name, so if you just use self.request.POST.get('attachments'), you'll only get one of them.

like image 20
Xiao Hanyu Avatar answered Oct 03 '22 07:10

Xiao Hanyu