Upload a file in Swagger and receive at Flask backend

蓝咒 提交于 2019-12-22 08:44:50

问题


I'm trying to upload a file using Swagger and Flask. I've the following configuration for swagger.

"/user/register/": {
    "post": {
        "tags": ["user"],
        "summary": "Register a new user",
        "description": "",
        "operationId": "registerUser",
        "consumes": ["application/json"],
        "produces": ["application/json"],
        "parameters": [{
            "in": "body",
            "name": "body",
            "description": "User object that needs to be added.",
            "required": true,
            "schema": {
                "$ref": "#/definitions/User"
            }
        },
        {
            "name": "file",
            "in": "path",
            "description": "file to upload",
            "required": true,
            "type": "file"
        }]
    }
},

I do get the option for uploading a file, but when I try to receive it at the backend,(using print request.files) it returns me nothing.

How can I receive the file (selected at swagger level) at the backend.??


回答1:


iFile = request.files.getlist('file')[0]- This command reads the file uploaded via swagger UI.




回答2:


For file, the type should be formData instead of path. See below for an example

      {
        "name": "file",
        "in": "formData",
        "description": "file to upload",
        "required": false,
        "type": "file"
      }

ref: https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.json#L384

For consumes, it should be multipart/form-data



来源:https://stackoverflow.com/questions/32495543/upload-a-file-in-swagger-and-receive-at-flask-backend

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