在使用easy_admin和@Vich\Uploadable进行镜像上传时,生成的哈希可以在上传完成后进行删除。这种操作可以确保镜像的安全性和减少存储空间的占用。
首先,需要了解easy_admin和@Vich\Uploadable的概念和用途:
针对这个问题,我们假设已经完成了easy_admin和@Vich\Uploadable的配置和安装。
步骤如下:
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @Vich\Uploadable
*/
class Image
{
/**
* @Vich\UploadableField(mapping="images", fileNameProperty="imageName")
*
* @var File
*/
private $imageFile;
/**
* @ORM\Column(type="string", length=255)
*
* @var string
*/
private $imageName;
// ...
}
easy_admin:
entities:
Image:
class: App\Entity\Image
form:
fields:
- { property: 'imageFile', type: 'file' }
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ImageController extends AbstractController
{
public function upload(Request $request)
{
$image = new Image();
$form = $this->createForm(ImageType::class, $image);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 处理文件上传
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($image);
$entityManager->flush();
// 删除生成的哈希
$image->setImageFile(null);
$entityManager->persist($image);
$entityManager->flush();
return $this->redirectToRoute('image_show', ['id' => $image->getId()]);
}
return $this->render('image/upload.html.twig', [
'form' => $form->createView(),
]);
}
}
{# templates/image/upload.html.twig #}
{% extends 'base.html.twig' %}
{% block body %}
<h1>上传图片</h1>
{{ form_start(form) }}
{{ form_row(form.imageFile) }}
<button type="submit">上传</button>
{{ form_end(form) }}
{% endblock %}
# config/routes.yaml
image_upload:
path: /image/upload
controller: App\Controller\ImageController::upload
methods: [GET, POST]
这样,当访问/image/upload路径时,将会显示一个上传表单,上传完成后会自动删除生成的哈希值。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云