【问题标题】:Handling or accessing file on in the RequestHandler uploaded in the POST request在 POST 请求中上传的 RequestHandler 中处理或访问文件
【发布时间】:2022-01-08 09:54:53
【问题描述】:

通过邮递员的 POST 请求,我正在发送带有参数的多部分/表单数据以及文件附件。现在在后端我使用龙卷风来处理这些请求,我使用RequestHandler.get_argument("str")(邮递员截图的第一个超链接)访问参数没有问题,但是我正在努力访问/读取来自同一请求的文件附件。根据龙卷风文档,我使用的是RequestHandler.get_body_argument.get_body_arguments,但两者似乎都不起作用。不确定我的后端是否遗漏了任何东西。有人可以帮忙吗?

Backend snippet:

dic = {}
dic['operation'] = RequestHandler.get_argument(self, name="operation"). << this is param in POST request from postman and I can get the value for key="operation" without any problem


但是如上图所示(第二个超链接到屏幕截图),使用 tornado 从后端的表单数据访问文件变得很困难。

【问题讨论】:

    标签: api postman multipartform-data tornado


    【解决方案1】:

    上传的文件在self.request.files下可用。

    class MyHandler(web.RequestHandler):
        def post(self):
            for field_name, files in self.request.files.items():
                for info in files:
                    filename = info['filename'] # name of the file
    
                    content_type = info['content_type'] # content type of the file
    
                    body = info['body'] # the data of the file
    
                    # do something ...
    

    【讨论】:

    • Ahhhhh 我没有意识到 self.request.files 是一个字典。好的,这应该可以。非常感谢,让我尝试更新。
    • 出于某种原因 self.request.files 是一个空字典。但是我使用 self.request.body.decode 转储了我收到的整个正文,它显示文件名作为键和值作为实际文件名。不确定内容类型是否不应该是“应用程序/json”。在我的情况下就是这种内容类型
    • @kittu 你的意思是请求的内容类型是application/json?如果是这样,你不能上传这样的文件。将文件作为base64 数据发送,或使用内容类型application/x-www-form-urlencodedenctype=multipart/form-data
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2011-10-03
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多