在EasyAdmin3 Symfony4中上传照片的问题可以通过以下步骤来解决:
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @ORM\Entity
* @Vich\Uploadable
*/
class YourEntity
{
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $photo;
/**
* @Vich\UploadableField(mapping="entity_photo", fileNameProperty="photo")
* @var File
*/
private $photoFile;
// getter and setter methods for $photo and $photoFile
// ...
}
composer require vich/uploader-bundle
# config/packages/vich_uploader.yaml
vich_uploader:
db_driver: orm
mappings:
entity_photo:
uri_prefix: /photos
upload_destination: '%kernel.project_dir%/public/photos'
namer: Vich\UploaderBundle\Naming\OrignameNamer
inject_on_load: true
delete_on_update: true
delete_on_remove: true
# config/packages/easy_admin.yaml
easy_admin:
entities:
YourEntity:
class: App\Entity\YourEntity
form:
fields:
- { property: 'name' }
- { property: 'photoFile', type: 'file', label: 'Photo' }
// src/Controller/YourEntityController.php
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class YourEntityController extends AbstractCrudController
{
public function configureFields(string $pageName): iterable
{
// ...
yield TextField::new('name');
yield AssociationField::new('photoFile')->setFormType(VichImageType::class);
}
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
if ($entityInstance instanceof YourEntity) {
// Handle file upload
$photoFile = $entityInstance->getPhotoFile();
if ($photoFile instanceof UploadedFile) {
$entityInstance->setPhoto($photoFile->getClientOriginalName());
}
}
parent::updateEntity($entityManager, $entityInstance);
}
}
<!-- templates/admin/your_entity/edit.html.twig -->
{% extends '@EasyAdmin/default/edit.html.twig' %}
{% block body_id 'easyadmin-edit-YourEntity' %}
{% block body_content %}
<h1>{{ block('page_title') }}</h1>
{{ form_start(edit_form) }}
{{ form_row(edit_form.name) }}
{{ form_row(edit_form.photoFile) }}
{# ... other fields ... #}
<button class="btn btn-primary" type="submit">{{ 'Save'|trans }}</button>
<a href="{{ path('admin', { entity: 'YourEntity' }) }}" class="btn btn-secondary">{{ 'Cancel'|trans }}</a>
{{ form_end(edit_form) }}
{% endblock %}
现在,你就可以在EasyAdmin3 Symfony4中成功上传照片了。请注意,上述代码中没有提及任何特定的云计算品牌商,但你可以通过使用相应的云存储服务,如腾讯云对象存储(COS),将上传的照片存储在云端。
原文地址 https://www.aiprose.com/blog/126 1 介绍 pug 是一种前端模板引擎,原名 jade 可用来生成 HTML,它的写法类似于 CSS 这里先简单举几个例子 #hello a.link-button Link Link 易理解,同时极大的简约了我们的代码。 2 安装 2.1 下载 npm i -D pug pug-html-loader pug-plain-l
领取专属 10元无门槛券
手把手带您无忧上云