通过表单上传图像的方式与预期的一样。 imageName,imageSize和updatedAt字段在数据库中按原样更改。但是,当尝试将上传的图像渲染到树枝模板中时,它会将imageFile返回为null
QuestionType表单类:
<select disabled.bind="array[$index].disabled">
问题实体:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('question', null, array('label'=>'Klausimas'))
->add('answer', null, array('label'=>'Atsakymas'))
->add('categoryName',null, array('label'=> 'Kategorija'))
->add('imageFile', VichImageType::class, array(
'allow_delete'=>false,
'download_uri'=>false
));
}
config.yml
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Question
*
* @ORM\Table(name="question")
* @ORM\Entity(repositoryClass="AppBundle\Repository\QuestionRepository")
* @Vich\Uploadable
*/
class Question
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @var string
*/
private $imageName;
/**
* @Vich\UploadableField(mapping="images", fileNameProperty="imageName", size="imageSize")
* @var File
*/
private $imageFile;
/**
* @ORM\Column(type="integer")
* @var integer
*/
private $imageSize;
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
private $updatedAt;
/**
* @param File|UploadedFile $imageName
* @throws \Exception
*/
public function setImageFile(?File $imageName = null): void
{
$this->imageFile = $imageName;
if (null !== $imageName){
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
public function setImageName(?string $imageName): void
{
$this->imageName = $imageName;
}
public function getImageName(): ?string
{
return $this->imageName;
}
public function setImageSize(?int $imageSize): void
{
$this->imageSize = $imageSize;
}
public function getImageSize(): ?int
{
return $this->imageSize;
}
}
用于编辑的枝条模板(上传图片):
vich_uploader:
db_driver: orm
mappings:
images:
uri_prefix: /images
upload_destination: '%kernel.project_dir%/web/images'
delete_on_update: false
应该显示它的树枝模板:
{{ form_start(edit_form) }}
{{ form_widget(edit_form, {'multipart': 'true'} ) }}
<input style="margin-top: 10px" type="submit" value="Išsaugoti" class="btn btn-success" />
{{ form_end(edit_form) }}
我的第一个猜测是我在错误的地方为我的表单添加了多部分(或者使用了错误的语法),但我找不到(或者没有得到)正确的设置方法
Firefox说:当我将鼠标放在开发工具中的标签上时无法加载图像
Chrome说:
获取http://helper/images/index%20-%20Copy.jpg 404(未找到)
修改
我发现 <img src="{{ vich_uploader_asset(question, 'imageFile', 'AppBundle\\Entity\\Question') }}"/>
已将表单设置为多部分,因此无需在此处传递选项{{ form_start(edit_form}}
。只要将其留在上面,任何其他人都会尝试将其作为解决方案