Home > Blockchain >  Edit file using POST Method with API Platform
Edit file using POST Method with API Platform

Time:04-21

In API Platform documentation it says:

Uploading files won't work in PUT or PATCH requests, you must use POST method to upload files.

But when i try to "force" method:

#[ORM\Entity(repositoryClass: CompanyRepository::class)]
#[ApiResource(
    itemOperations: [
        "put" => ['method' => 'POST']
    ],
    denormalizationContext: ['groups' => ['write']],
    normalizationContext: ['groups' => ['read']]
)]
/**
 * @Vich\Uploadable
 */
class Company implements ImageInterface

I got

There is no builtin action for the item POST operation. You need to define the controller yourself

Any idea how to transform PUT to POST?

CodePudding user response:

POST operation are Collection operations, not item operations.

As per: https://github.com/api-platform/api-platform/issues/1663

CodePudding user response:

One solution is (after following documentation https://api-platform.com/docs/core/file-upload/#uploading-to-an-existing-resource-with-its-fields) to create a custom operation with POST method, and an empty controller: entity/company.php

#[ApiResource(
    itemOperations: [
        "get" => ApiConstInterface::UNSECURE,
        'edit_file' => ApiConstInterface::SECURE_ADMIN_AND_OWNER
              [
                'method' => 'POST',
                'controller' => EditCompany::class,
                'input_formats' => [
                    'multipart' => ['multipart/form-data'],
                ],
            ],
        "delete" => ApiConstInterface::SECURE_ADMIN_AND_OWNER,
    ],
    denormalizationContext: ['groups' => ['write']],
    normalizationContext: ['groups' => ['read']]
)]
/**
 * @Vich\Uploadable
 */
class Company implements ImageInterface

controller/EditCompany.php

#[AsController]
final class EditCompany extends AbstractController
{
    public function __invoke(Company $data): Company
    {
        return $data;
    }
}
  • Related