为每个实体上传多个文件

时间:2015-02-20 14:42:03

标签: symfony doctrine-orm

我正在使用doctrine2和symfony2。

这是我上传文件的实体。

首先,它调用setFile()并将路径放到$ this-> temp,

然后,调用preUpload,调用上传。

可以为每个实体上传一个文件,但是,我想为每个实体上传多个文件。

我该如何处理?

你有没有为此目的的样品?

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $path = "nophoto.jpeg";

/**
 * @Assert\File(maxSize="6000000")
 */
private $file;

public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
    // check if we have an old image path
    if (is_file($this->getAbsolutePath())) {
        // store the old name to delete after the update
        $this->temp = $this->getAbsolutePath();
    } else {
        $this->path = 'initial';
    }
}

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */

public function preUpload()
{
    if (null !== $this->getFile()) {
    $this->path = $this->getId().'.'.$this->getFile()->guessExtension();
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */

public function upload()

{
    if (null === $this->getFile1()) {return;}
    if (isset($this->temp)) {
        // delete the old image
        unlink($this->temp);
        // clear the temp image path
        $this->temp = null;
    }
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->getId().'.'.$this->getFile()->guessExtension()
    );
    $this->setFile(null);
}

public function getAbsolutePath()
{
    return null === $this->path
    ? null
    : $this->getUploadRootDir().'/'.$this->getId().'.'.$this->path;
}
public function getFile1()
{
    return $this->file;
}

public function getWebPath()
{
    return null === $this->path
    ? null
    : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}

1 个答案:

答案 0 :(得分:1)

您需要新的实体,它代表上传的文件与您的实体的多对一(或多对多)关联。这是最普遍的方法。

或者,您可以将文件名存储在数组中,但这会使验证和表单复杂化。