Как загрузить файл в массив swagger- php - PullRequest
1 голос
/ 13 июля 2020

Я хочу загрузить файл в формате swagger- php в json requestBody Как можно загрузить с помощью анонсов Swagger

Пробуем много часов, но не повезло, как отправить application / json array Можете ли вы помочь, если какая-либо информация об этом, тогда я решу свою проблему, я понятия не имею об этом

, когда этот код, генерируемый в терминале, также не имеет никакой ошибки и не отображается в тело запроса в пользовательском интерфейсе swagger

/**
* @OA\Post(
*      path="/products/save",
*      tags={"Product"},
*      summary="Post bulk products",
*      description="Return bulk products",
*      @OA\RequestBody(
*       required=true,
*       description="Bulk products Body",
*       @OA\JsonContent(
*           @OA\Property(
*               property="products",
*               @OA\Items(
*                  @OA\Property(property="first_name", type="string"),
*                  @OA\Property(property="last_name", type="string"),
*                  @OA\Property(property="email", type="string"),
*                  @OA\Property(property="phone", type="string"),
*                  @OA\Property(property="resume", type="string", format="base64"),
*               ),
*           )
*       )
*     ),
* )
*/

Я хочу использовать этот тип тела swagger-ui, чтобы пользователь мог заполнить атрибут и добавить резюме в формате base64

{
  "products": [
    {
      "first_name": "string",
      "last_name": "string",
      "email": "string",
      "phone": "string",
      "resume": "string" ==> here i will send base64 format of resume file
    }
  ]
}
``

Ответы [ 2 ]

2 голосов
/ 13 июля 2020

Вы можете использовать @OA\Property(property="file", type="string", format="binary"), для определения свойства файла:

/**
 * @OA\Schema(
 *   schema="ProductRequest",
 *   required={"products"},
 *   @OA\Property(
 *       property="products",
 *       type="array",
 *       @OA\Items(
 *           @OA\Property(property="first_name", type="string"),
 *           @OA\Property(property="last_name", type="string"),
 *           @OA\Property(property="email", type="string"),
 *           @OA\Property(property="phone", type="string"),
 *           @OA\Property(property="resume", type="string", format="binary"),
 *       ),
 *    )
 * )
 */

Затем вы должны установить тип носителя на вашем RequestBody, используя @OA\MediaType:

/**
 * @OA\RequestBody(
 *   request="Product",
 *   required=true,
 *   description="Bulk products Body",
 *   @OA\MediaType(
 *     mediaType="multipart/form-data",
 *     @OA\Schema(ref="#/components/schemas/ProductRequest")
 *   )
 * )
 */

И, наконец, на вашем @OA\Post:

/**
 * @OA\Post(
 *   path="/products/save",
 *   tags={"Product"},
 *   summary="Post bulk products",
 *   description="Return bulk products",
 *   @OA\RequestBody(ref="#/components/requestBodies/Product"),
 *   @OA\Response(response=200, ref="#/components/responses/Product")
 * )
 */

См. Также документацию Swagger на Тип данных файла и Загрузка файла для получения дополнительной информации.

Обновление: если вам не нужны отдельные объявления, просто объедините их следующим образом:

/**
 * @OA\Post(
 *   path="/products/save",
 *   tags={"Product"},
 *   summary="Post bulk products",
 *   description="Return bulk products",
 *   @OA\RequestBody(
 *     required=true,
 *     description="Bulk products Body",
 *     @OA\MediaType(
 *       mediaType="multipart/form-data",
 *       @OA\Schema(
 *         @OA\Property(
 *           property="products",
 *           type="array",
 *           @OA\Items(
 *             @OA\Property(property="first_name", type="string"),
 *             @OA\Property(property="last_name", type="string"),
 *             @OA\Property(property="email", type="string"),
 *             @OA\Property(property="phone", type="string"),
 *             @OA\Property(property="resume", type="string", format="binary"),
 *           )
 *         )
 *       )
 *     )
 *   )
 * )
 */
0 голосов
/ 13 июля 2020

Вам также может потребоваться подход с PHP классы

Таким образом, вы можете определить такую ​​модель:

/**
 * @OA\Schema(
 *     schema="User",
 *     required={"first_name", "last_name" // and so on}
 *  )
 */
class User 
{
    /**
     * @OA\Property(type="string")
     */
    public $first_name;

     /**
     * @OA\Property(type="string")
     */
    public $last_name;

    // add your other fields bellow
}

после того, как вы можете определить, например, тело запроса POST следующим образом:

<?php

/**
 * @OA\Schema(
 *     schema="CreateUsers",
 *     required={"users"}
 *  )
 */
class CreateUsers
{

    /**
     * @var array
     * @OA\Property(ref="#/components/schemas/User")
     */
    public $users;
}

И, наконец, создайте запрос в своей документации, например:

/**
 * @OA\Post(
 *      path="YOUR ROUTE URL",
 *      operationId="createUsers",
 *      tags={"Users"},
 *      @OA\RequestBody(
 *         required=true,
 *         @OA\MediaType(
 *             mediaType="application/json",
 *             @OA\Schema(ref="#/components/schemas/CreateUsers")
 *         )
 *     ),
 *      summary="Create a collection of users",
 *      description="Create a collection of users"
 *    )
 **/

EDIT 1:

Если вы хотите, чтобы у вас был файл в теле запроса:

/**
 * @OA\Post(
 *      path="YOUR ROUTE URL",
 *      operationId="createUsers",
 *      tags={"Users"},
 *      @OA\RequestBody(
 *         required=true,
 *         @OA\MediaType(
 *             mediaType="multipart/form-data", // here we need to change from "application/json" to "multipart/form-data" in order to make our file visible
 *             @OA\Schema(ref="#/components/schemas/CreateUsers")
 *         )
 *     ),
 *      summary="Create a collection of users",
 *      description="Create a collection of users"
 *    )
 **/

И сделайте свое поле в своем PHP классе:

/**
 * @OA\Schema(
 *     schema="User",
 *     required={"first_name", "last_name", "file" // and so on}
 *  )
 */
class User 
{
    /**
     * @OA\Property(type="string")
     */
    public $first_name;

     /**
     * @OA\Property(type="string")
     */
    public $last_name;

     /**
     * @OA\Property(description="file to upload", type="string", format="file")
     */
    public $file;

    // add your other fields bellow
}

Вы можете видеть пример здесь: swagger-php / Примеры / petstore.swagger.io / controllers / PetController. php

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...