user4488093
user4488093

Reputation:

SonataAdminBundle files uplaod to /tmp

When I load the files in SonataAdminBundle they are loaded into the tmp folder I have this entity:

   /**
     *
     * @var string
     *
     * @ORM\Column(type="text", length=255, nullable=false)
     */
    protected $path;

    /**     
     * @var File
     *
     * @Assert\File(
     *     maxSize = "5M",
     *     mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/tiff"},
     *     maxSizeMessage = "The maxmimum allowed file size is 5MB.",
     *     mimeTypesMessage = "Only the filetypes image are allowed."
     * )
     */
    protected $file;

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    /**
     * @return File
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @param File $file
     */
    public function setFile($file)
    {
        $this->file = $file;
    }

    /**
     *
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->file) {
            // do whatever you want to generate a unique name
            $filename = sha1(uniqid(mt_rand(), true));
            $this->path = $filename.'.'.$this->file->guessExtension();
        }
    }

    /**
     *
     * @ORM\PreRemove()
     */
    public function removeUpload()
    {
        if ($file = $this->getAbsolutePath()) {
            unlink($file);
        }
    }

    /**
     * Called after entity persistence
     *
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            return;
        }

        $this->file->move(
            $this->getUploadRootDir(),
            $this->path
        );


        $this->path = $this->file->getClientOriginalName();

        $this->file = null;
    }

And this form in Admin class:

$formMapper
    ->add('name', 'text', [
        'label' => 'Name'
    ])
    ->add('address', 'text', [
        'label' => 'Address'
    ])
    ->add('description', 'text', [
        'label' => 'Description'
    ])
    ->add('file', 'file', [
        'label' => 'Image',
        'data_class' => null
    ])

;

When I load the file in the admin panel, and then look in the database then the column path: /tmp/php1w6Fvb

Upvotes: 0

Views: 187

Answers (1)

BENARD Patrick
BENARD Patrick

Reputation: 30985

Yes it's normal.

I recommend you to read this part of official Symfony documentation about file upload.

Your file is upload to /tmp. If you sent it directly to DB without store it in another directory, it's lost.

official doc : http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

It show you how to store it...

Upvotes: 1

Related Questions