FOS用户文件上传

时间:2014-07-14 06:58:09

标签: php symfony fosuserbundle sonata-admin

我正在使用Symfony2.3 + Sonata Admin + FosUserBundle + SonataUserBundle。 Everthing工作正常。

在用户中:我创建了用户图片上传功能,这个功能非常好,当用户上传他的图片然后上传路径

/web/uoloads/documents/imagesname.jpg

我想更改此路径,并在s3上上传所有用户图片。

这是用户实体: -

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

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

/**
 * @Assert\Image(maxSize="6000000", mimeTypesMessage="Please select a valid image")
 */
private $file;

public function __construct()
{
    parent::__construct();

}

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

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';
}


/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
}

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

public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
    return;
} 

// use the original file name here but you should
// sanitize it at least to avoid any security issues

// move takes the target directory and then the
// target filename to move to
$this->getFile()->move(
    $this->getUploadRootDir(),
    $this->getFile()->getClientOriginalName()
);

// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();

// clean up the file property as you won't need it anymore
$this->file = null;
}

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

    return $this;
}

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

}

我通过实体中的服务容器更改此路径,但是正常的调用服务conatiner(例如此Get service container from entity in symfony 2.1 (Doctrine))无效并且在FOS用户中显示错误。

我很困惑。任何人都建议我如何改变这条道路并转向s3。如果成功调用用户实体中的服务容器,那么我的问题就解决了,但正常的symfony服务调用在FOS用户包中不起作用。

谢谢!

1 个答案:

答案 0 :(得分:0)

为什么不使用VichUploaderBundle?与Flysystem / Gaufrette相关联,很容易将上传的文件链接到实体并将它们发送到S3,FTP,无论如何。