How to handle uploaded files in webapp2

☆樱花仙子☆ 提交于 2019-12-05 04:13:44

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.

Xiao Hanyu

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.

fccoelho

Instead of using the solution described in How does cgi.FieldStorage store files?, I used enctype="multipart/form-data" in the form, and

in the handler method for the post I accessed the files via:

file_content = self.request.POST.multi['myfieldname'].file.read()

it worked!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!