Search code examples
phpsymfonysymfony4

Symfony 4.2 Uploaded Files and Renaming them


Need a bit of help from you with this Symfony web api i'm building. Long story short it uses the API-Platform on top of Symfony. Following the documentation I added in the ability to post files however the problem i'm running into is collisions. I need a good way to rename the files. The files are served as UploadedFile classes.

That said I know about the move function and i've tried this however with my current setup this is not a good option.

Sample of controller code:

        public function __invoke(Request $request): Images
        {
            $uploadedFile = $request->files->get('file');
            if (!$uploadedFile) {
                throw new BadRequestHttpException('"file" is required');
            }
            $mediaObject = new Images();
            $mediaObject->file = $uploadedFile;
            ...
            $this->validate($mediaObject, $request);

            $em = $this->managerRegistry->getManager();
            $em->persist($mediaObject);
            $em->flush();

            return $mediaObject;
        }

Images Entitiy:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use App\Controller\CreateMediaObjectAction;

/**
 * @ApiResource(
 *     iri="http://schema.org/Images",
 *     collectionOperations={
 *         "post"={
 *             "controller"=CreateMediaObjectAction::class,
 *             "defaults"={
 *                 "_api_receive"=false,
 *             },
 *             "validation_groups"={"Default", "media_object_create"},
 *             "swagger_context"={
 *                 "consumes"={
 *                     "multipart/form-data",
 *                 },
 *                 "parameters"={
 *                     {
 *                         "in"="formData",
 *                         "name"="file",
 *                         "type"="file",
 *                         "description"="The file to upload",
 *                     },
 *                 },
 *             },
 *         },
 *         "get",
 *     },
 *     itemOperations={
 *         "get",
 *     },
 * )
 * @Vich\Uploadable
 * @ORM\Entity(repositoryClass="App\Repository\ImagesRepository")
 */
class Images
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $dealer_id;

    /**
     * @var File|null
     *
     * @Assert\NotNull(groups={"media_object_create"})
     * @Vich\UploadableField(mapping="images", fileNameProperty="image_path")
     */
    public $file;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image_path;

    /**
     * @ORM\Column(type="datetime")
     */
    private $created_on;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $unique_id;

    public function getFile()
    {
        return $this->file;
    }

    /**
     * @param string $file
     *
     * @return Images
     * @throws \Exception
     */
    public function setFile(string $file): self
    {
        $this->file = $file;

        return $this;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDealerId(): ?int
    {
        return $this->dealer_id;
    }

    public function setDealerId(int $dealer_id): self
    {
        $this->dealer_id = $dealer_id;

        return $this;
    }

    public function getImagePath(): ?string
    {
        return $this->image_path;
    }

    public function setImagePath(string $image_path): self
    {
        $this->image_path = $image_path;

        return $this;
    }

    public function getCreatedOn(): ?\DateTimeInterface
    {
        return $this->created_on;
    }

    public function setCreatedOn(\DateTimeInterface $created_on): self
    {
        $this->created_on = $created_on;

        return $this;
    }

    public function getUniqueId(): ?string
    {
        return $this->unique_id;
    }

    public function setUniqueId(string $unique_id): self
    {
        $this->unique_id = $unique_id;

        return $this;
    }
}

So the question being is there a good way to rename a file posted to the Symfony application without using the move function?


Solution

  • Found a solution that works for me: https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/namers.md#file-namer

    VichUp has a built in service for renaming files automatically to avoid collisions as well as directory planing.

    Hope it can help someone else.