我正在尝试使用FOSUser Bundle注册后添加默认个人资料图片。但是,我不知道如何在我的__construct中添加这种文件,因为它是一个所需的图像映射实体。
这是我的用户实体:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*
* @Assert\NotBlank(message="L'image doit être au format jpg")
* @Assert\File( maxSize = "100k",mimeTypes={ "image/jpg" })
*/
private $image;
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
return $this;
}
public function __construct()
{
parent::__construct();
// your own logic
$this->image = 'http://lorempixel.com/300/300/';
}
}
我尝试改编:https://symfony.com/doc/current/controller/upload_file.html
答案 0 :(得分:0)
以下行“$ this-&gt; image ='http://lorempixel.com/300/300/';”当验证程序尝试使用“@Assert \ File(...)验证该字段时,将字符串放入图像字段中)“它失败了,因为他找到了一个字符串而不是一个文件
您需要做的是将文件类型放入该字段,如下所示:
use Symfony\Component\HttpFoundatio\File\UploadedFile;
class User extends BaseUser
.....
public function __construct()
{
parent::__construct();
$this->image = new UploadedFile("http://lorempixel.com/300/300/", "defaultImg");
}
}
第一个参数是文件的路径,第二个参数是该文件的名称,请检查UploadedFile类的Symfony API参考: http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/File/UploadedFile.html
我假设你使用@Assert \ Image约束而不是@Assert \ File约束,这里解释了它:http://symfony.com/doc/current/reference/constraints/Image.html