Sonata Admin Bundle 文件上传到 /tmp

SonataAdminBundle files uplaod to /tmp

当我加载 SonataAdminBundle 中的文件时,它们被加载到 tmp 文件夹中 我有这个实体:

   /**
     *
     * @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;
    }

Adminclass中的这个表格:

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

;

当我在管理面板中加载文件,然后在数据库中查看列 path:/tmp/php1w6Fvb

是的,这很正常。

我建议你阅读这部分官方 Symfony 文件上传文档

您的文件正在上传到 /tmp。如果您直接将其发送到 DB 而未将其存储在另一个目录中,则它会丢失。

官方文档: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

它告诉你如何存储它...