SonataMediaBundle:如何添加svg文件扩展名 [英] SonataMediaBundle: How to add svg file extension

查看:97
本文介绍了SonataMediaBundle:如何添加svg文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在配置中添加 .svg 文件扩展名.

I need to add .svg file extension to my configuration.

目前,在我的项目中,我还有其他扩展名(例如,pdf,图像)

At the moment in my project I have other extensions as (pdf, images)

我进行了以下更改

  1. 上下文
  2. 中添加了新的svg_file
  3. 添加了文件提供程序(在配置文件的末尾)
  4. allowed_extensions
  5. 中添加了svg
  6. allowed_mime_types
  7. 添加了图像/svg + xml
  1. Added a new svg_file to the context
  2. Added the file provider (In the end of configuration file)
  3. Added the svg in allowed_extensions
  4. Added the image/svg+xml in allowed_mime_types

现在,我可以上载svg文件了,但问题是用户可以上载其他文件扩展名,例如pdf等.

Now, I can upload the svg file but the problem is that the user can upload other file extensions for example pdf etc..

如何避免呢?还是找到正确的表单验证方式?

How can avoid it? Or find a proper way for the form validation?

Sonata文档:

媒体环境

对我有帮助,但对表单验证没有帮助.

helped me, but not for the form validation.

我缺少什么?

我更改了以下文件:

#app/config/sonata_config.yml

sonata_media:
default_context: images_file
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr
contexts:
    pdf_file:
        providers:
            - sonata.media.provider.file
        formats: ~
    images_file:
        providers:
            - sonata.media.provider.image
        formats:
            1x: { width: 870 , height: 412 , quality: 80 }
            2x: { width: 1740 , height: 824 , quality: 50 }
    svg_file:
        providers:
            - sonata.media.provider.file
        formats: ~
    cdn:
        server:
          path: /uploads/media # http://media.sonata-project.org/

    filesystem:
        local:
           directory:  %kernel.root_dir%/../web/uploads/media
           create:     false

    providers:
        file:
           service:    sonata.media.provider.file
           resizer:    false
           filesystem: sonata.media.filesystem.local
           cdn:        sonata.media.cdn.server
           generator:  sonata.media.generator.default
           thumbnail:  sonata.media.thumbnail.format
           allowed_extensions: ['pdf', 'txt', 'rtf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pttx', 'odt', 'odg', 'odp', 'ods', 'odc', 'odf', 'odb', 'csv', 'xml','svg']
           allowed_mime_types: ['application/pdf', 'application/x-pdf', 'application/rtf', 'text/html', 'text/rtf', 'text/plain', 'image/svg+xml']

表单文件:

use Sonata\AdminBundle\Admin\Admin;
class CustomAdmin extends Admin
{
/**
 * @param FormMapper $formMapper
 */
protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add(
            'NormalLogo',
            'sonata_type_model_list',
            array('required' => false),
            array(
                'link_parameters' => array('context' => 'images_file', 'provider' => 'sonata.media.provider.image'),
            )
        )
        ->add(
            'SvgLogo',
            'sonata_type_model_list',
            array('required' => false),
            array(
                'link_parameters' => array('context' => 'svg_file', 'provider' => 'sonata.media.provider.file'),
            )
        )
        ->add('overriddenBy', 'sonata_type_model',
            array(
                'empty_value' => 'Not overridden',
                'btn_add' => false,
                'btn_list' => false,
                'btn_delete' => false,
                'btn_catalogue' => false,
            )
        );
}
}

推荐答案

您只能为SVG文件创建自己的提供程序,而您需要首先为SVG提供程序定义服务

You can create your own provider for SVG files only to do this you need to define a service first for your SVG provider

parameters:
    application_sonata_media.svg_class: Application\Sonata\MediaBundle\Provider\SVGProvider
services:
    sonata.media.provider.svg:
          class: %application_sonata_media.svg_class%
          tags:
              - { name: sonata.media.provider }
          arguments:
              - sonata.media.provider.svg
              - @sonata.media.filesystem.local
              - @sonata.media.cdn.server
              - @sonata.media.generator.default
              - @sonata.media.thumbnail.format
              - allowed_extensions: ['svg']
              - allowed_mime_types: ['image/svg+xml']

使用奏鸣曲,您可以使用 EASYEXTENDS BUNDLE 默认会在src/Application/Sonata/MediaBundle中生成扩展包,但您也可以指定其他目标.现在,在扩展媒体包的services.yml中创建上述服务,然后导入主config.yml.如果要添加更多的mime类型或您可以在上述服务allowed_mime_types: ['image/svg+xml','application/pdf']

Using sonata you can generate extended bundles using EASYEXTENDS BUNDLE by default it generates extended bundle in src/Application/Sonata/MediaBundle but you can specify other destination as well.Now create above service in extended media bundle's services.yml and import in main config.yml.If you want to add more mime types or extensions you can define in above service allowed_mime_types: ['image/svg+xml','application/pdf']

imports:
    - { resource: @ApplicationSonataMediaBundle/Resources/config/services.yml }

现在在扩展媒体束中将提供程序类创建为SVGProvider,并使用sonata media的FileProvider

Now create your provider class in your extended media bundle as SVGProvider and extend your provider class with sonata media's FileProvider

<?php
namespace Application\Sonata\MediaBundle\Provider;

use Sonata\MediaBundle\Provider\FileProvider as BaseFileProvider;
use Gaufrette\Filesystem;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\MediaBundle\CDN\CDNInterface;
use Sonata\MediaBundle\Generator\GeneratorInterface;
use Sonata\MediaBundle\Metadata\MetadataBuilderInterface;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;

class SVGProvider extends BaseFileProvider {
    protected $allowedMimeTypes;
    protected $allowedExtensions;
    protected $metadata;

    public function __construct( $name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, array $allowedExtensions = array(), array $allowedMimeTypes = array(), MetadataBuilderInterface $metadata = null ) {
        parent::__construct( $name, $filesystem, $cdn, $pathGenerator, $thumbnail );

        $this->allowedExtensions = $allowedExtensions;
        $this->allowedMimeTypes  = $allowedMimeTypes;
        $this->metadata          = $metadata;
    }

    public function buildCreateForm( FormMapper $formMapper ) {
        $formMapper->add( 'binaryContent', 'file', array(
            'label'       => 'Upload SVG file only',
            'constraints' => array(
                new NotBlank(),
                new NotNull(),
            ),
        ) );
    }

    /**
     * {@inheritdoc}
     */
    public function validate( ErrorElement $errorElement, MediaInterface $media ) {

        if ( ! $media->getBinaryContent() instanceof \SplFileInfo ) {
            return;
        }

        if ( $media->getBinaryContent() instanceof UploadedFile ) {
            $fileName = $media->getBinaryContent()->getClientOriginalName();
        } elseif ( $media->getBinaryContent() instanceof File ) {
            $fileName = $media->getBinaryContent()->getFilename();
        } else {
            throw new \RuntimeException( sprintf( 'Invalid binary content type: %s', get_class( $media->getBinaryContent() ) ) );
        }

        if ( ! in_array( strtolower( pathinfo( $fileName, PATHINFO_EXTENSION ) ), $this->allowedExtensions ) ) {
            $errorElement
                ->with( 'binaryContent' )
                ->addViolation( 'Invalid extensions' )
                ->end();
        }

        if ( ! in_array( $media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes ) ) {
            $errorElement
                ->with( 'binaryContent' )
                ->addViolation( 'Invalid mime type : ' . $media->getBinaryContent()->getMimeType() )
                ->end();
        }
    }
}

在这里您可以覆盖基类函数并根据需要定义自己的功能,例如,要对文件输入添加一些验证,可以自定义validate()函数以更改文件输入字段的属性,可以在方法

Here you can override base class functions and define your own functionality as you wish for example you want to add some validations to file input you can customize validate() function to change attributes for file input field you can define it in buildCreateForm() method

现在,如果您只想允许SVG上传,则可以在管理员中定义自己的提供商,该提供商仅允许SVG文件

Now in your admin if you want to allow only SVG to upload you can define your own provider which allows only SVG files

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add(
            'SvgLogo',
            'sonata_type_model_list',
            array('required' => false),
            array(
                'link_parameters' => array('context' => 'svg_file', 'provider' => 'sonata.media.provider.svg'),
            )
        )
}

这篇关于SonataMediaBundle:如何添加svg文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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