如何处理webapp2中上载的文件

2024-05-14 03:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

Google appengine的webapp2有一个非常神秘的documentation regarding the handling of uploaded files

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

我有一个表单,它对JSON文件发出POST请求,我希望将其存储在NDB.JsonProperty中。

有谁能提供一个简短的例子说明我如何从请求对象读取文件吗?


Tags: 文件ofthedocumentationgooglefilespostare
3条回答

谷歌的文档太糟糕了。我花了大约两个小时来尝试webapp2的request对象,最后找到了一种方法。

检查https://stackoverflow.com/a/30969728/2310396

基本代码片段如下:

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

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

我们使用self.request.POST.getall('attachments')而不是self.request.POST.get('attachments'),因为它们可能是同名HTML表单中的多个input字段,所以如果只使用self.request.POST.get('attachments'),则只能得到其中一个。

您可以在表单中使用enctype="multipart/form-data",然后通过在处理程序中使用获取文件内容:

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

然后,将原始文件作为输入传递到模型的属性。

我没有使用How does cgi.FieldStorage store files?中描述的解决方案,而是在表单中使用enctype=“multipart/form data”,并且

在post的handler方法中,我通过以下方式访问了这些文件:

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

成功了!

相关问题 更多 >