首页 > 解决方案 > 使用带有验证器的 Vich Uploader 添加图像时,imageName 为 null

问题描述

当我使用带有验证的 vich 上传器上传图像时,它将返回“imageName 不应为空”错误消息。我无法弄清楚它造成这种情况的原因。


Vich 上传器配置:

vich_uploader:
    db_driver: orm

    mappings:
        home_partner_alliance:
            uri_prefix: /image/home/partnerAlliance
            upload_destination: '%kernel.project_dir%/public/image/home/partnerAlliance'

我的控制器:

/* 
  --- router annotation ---
*/
public function addImage(Request $request, ValidatorInterface $validator)
{
    $file = $request->files->get('image');
    $home = new HomePartnerAlliance();
    $home->setImageFile($file);
    $home->setUpdatedAt(new \DateTime());

    $errors = $validator->validate($home);
    if(count($errors) == 0){
        $this->em->persist($home);
        $this->em->flush();
    }
    else
    {
        $messages = [];
        foreach($errors as $error)
        {
            $messages[$error->getPropertyPath()] = $error->getMessage();
        }
    }

    return new JsonResponse(['status'=> $messages]);
}

我的实体:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\HomePartnerAllianceRepository")
 * @Vich\Uploadable
 */
class HomePartnerAlliance
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @Vich\UploadableField(mapping="home_partner_alliance", fileNameProperty="imageName")
 * @Assert\File(mimeTypes = {"image/jpeg", "image/png"})
 */
private $imageFile;

/**
 * @ORM\Column(type="string", length=255)
 */
private $imageName;

/**
 * @ORM\Column(type="date")
 */
private $updatedAt;

public function getId(): ?int
{
    return $this->id;
}

public function setImageFile(?File $imageFile = null): void
{
    $this->imageFile = $imageFile;

    if (null !== $imageFile) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime();
    }
}

public function getImageFile(): ?File
{
    return $this->imageFile;
}

public function getImageName(): ?string
{
    return $this->imageName;
}

public function setImageName(?string $imageName): self
{
    $this->imageName = $imageName;

    return $this;
}

public function getUpdatedAt(): ?\DateTimeInterface
{
    return $this->updatedAt;
}

public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
    $this->updatedAt = $updatedAt;

    return $this;
}
}

因此,当我将图像发布到控制器时,它会返回一条错误消息:

{
  "status": {
    "imageName": "This value should not be null."
  }
}

我尝试上传无效类型的文件,它也会返回 imageName Null:

{
  "status": {
    "imageFile": "The mime type of the file is invalid (\"image\/vnd.adobe.photoshop\"). Allowed mime types are \"image\/jpeg\", \"image\/png\".",
    "imageName": "This value should not be null."
  }
}

但是当我删除控制器中的验证代码时,它成功地将图像添加到文件夹中,并且图像名称被保存到数据库中。这个问题有什么解决办法吗?

标签: symfonydoctrinevichuploaderbundlesymfony-validator

解决方案


我认为您错过了namerVich 映射中的属性。

vich_uploader:
    db_driver: orm

    mappings:
        home_partner_alliance:
            uri_prefix: /image/home/partnerAlliance
            upload_destination: '%kernel.project_dir%/public/image/home/partnerAlliance'
            namer: Vich\UploaderBundle\Naming\UniqidNamer

推荐阅读