如何在VichUploader中使用mimeType声明? [英] How to use mimeType Assert with VichUploader?

查看:125
本文介绍了如何在VichUploader中使用mimeType声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 VichUploaderBundle 上传:

/**
 * @Vich\UploadableField(mapping="product_media", fileNameProperty="path")
 * @Assert\File(
 *     mimeTypes = {"image/jpeg", "image/gif", "image/png", "video/mp4", "video/quicktime", "video/avi"},
 *     mimeTypesMessage = "Wrong file type (jpg,gif,png,mp4,mov,avi)"
 * )
 * @var File $pathFile
 */
protected $pathFile;

我看不到断言的问题所在.如何使用VichUploader验证文件类型?

I cannot see what the problem is with the assert. How can I validate file types with VichUploader?

推荐答案

您可以使用验证回调来解决此问题.

You can use validation callback to solve this issue.

/**
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\EntityRepository")
 * @ORM\Table(name="entity")
 * @Assert\Callback(methods={"validate"})
 * @Vich\Uploadable
 */
class Entity
{
    /**
     * @Assert\File(maxSize="10M")
     * @Vich\UploadableField(mapping="files", fileNameProperty="fileName")
     *
     * @var File $file
     */
    protected $file;

    /**
     * @ORM\Column(type="string", length=255, name="file_name", nullable=true)
     *
     * @var string $fileName
     */
    protected $fileName;

...

    /**
     * @param ExecutionContextInterface $context
     */
    public function validate(ExecutionContextInterface $context)
    {
        if (! in_array($this->file->getMimeType(), array(
            'image/jpeg',
            'image/gif',
            'image/png',
            'video/mp4',
            'video/quicktime',
            'video/avi',
        ))) {
            $context
                ->buildViolation('Wrong file type (jpg,gif,png,mp4,mov,avi)')
                ->atPath('fileName')
                ->addViolation()
            ;
        }
    }
}

这篇关于如何在VichUploader中使用mimeType声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆