上传文件不起作用 - vich_uploader

时间:2017-08-04 05:45:55

标签: symfony vichuploaderbundle

我试图用vich_upload上传文件,但我不明白为什么图片没有更新:/

表单不返回错误,但图像未保存。我不明白为什么,虽然它没有给我任何错误..

我的代码可以告诉我哪里错了吗?

我提前感谢你

config.yml:

imports:
                - { resource: parameters.yml }
                - { resource: security.yml }
                - { resource: services.yml }

            # Put parameters here that don't need to change on each machine where the app is deployed
            # http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
            parameters:
                locale: fr
                app.path.partenaire_dir : /images/partenaires

            framework:
                #esi:             ~
                translator:      { fallbacks: ["%locale%"] }
                secret:          "%secret%"
                router:
                    resource: "%kernel.root_dir%/config/routing.yml"
                    strict_requirements: ~
                form:            ~
                csrf_protection: ~
                validation:      { enable_annotations: true }
                #serializer:      { enable_annotations: true }
                templating:
                    engines: ['twig']
                default_locale:  "%locale%"
                trusted_hosts:   ~
                trusted_proxies: ~
                session:
                    # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
                    handler_id:  session.handler.native_file
                    save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
                fragments:       ~
                http_method_override: true
                assets: ~

            # Twig Configuration
            twig:
                debug:            "%kernel.debug%"
                strict_variables: "%kernel.debug%"
                form_themes:
                    - 'SonataFormatterBundle:Form:formatter.html.twig'
                    - 'VichUploaderBundle:Form:fields.html.twig'
            # Doctrine Configuration
            doctrine:
                dbal:
                    driver:   pdo_mysql
                    host:     "%database_host%"
                    port:     "%database_port%"
                    dbname:   "%database_name%"
                    user:     "%database_user%"
                    password: "%database_password%"
                    charset:  UTF8
                    # if using pdo_sqlite as your database driver:
                    #   1. add the path in parameters.yml
                    #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
                    #   2. Uncomment database_path in parameters.yml.dist
                    #   3. Uncomment next line:
                    #     path:     "%database_path%"

                orm:
                    auto_generate_proxy_classes: "%kernel.debug%"
                    naming_strategy: doctrine.orm.naming_strategy.underscore
                    auto_mapping: true

            # Swiftmailer Configuration
            swiftmailer:
                transport: "%mailer_transport%"
                encryption: ssl
                auth_mode: login
                host:      "%mailer_host%"
                username:  "%mailer_user%"
                password:  "%mailer_password%"
                spool:     { type: memory }

            sonata_block:
                default_contexts: [cms]
                blocks:
                    # enable the SonataAdminBundle block
                    sonata.admin.block.admin_list:
                        contexts: [admin]
                    sonata.admin.block.search_result:
                        contexts: [admin]
                    sonata.block.service.text:
                    sonata.block.service.rss:

            fos_user:
                db_driver: orm # other valid values are 'mongodb' and 'couchdb'
                firewall_name: main
                user_class: AppBundle\Entity\User

            gregwar_captcha: 
                width: 200
                height: 50
                length: 6
                quality: 90
                distortion: true
                background_color: [41, 145, 214]
                max_front_lines: 0
                reload: true
                as_url: true
                interpolation: true

            ivory_ck_editor:
                default_config: default
                configs:
                        default:
                            toolbar: standard

            sonata_formatter:
                default_formatter: text
                formatters:
                    markdown:
                        service: sonata.formatter.text.markdown
                        extensions:
                            - sonata.formatter.twig.control_flow
                            - sonata.formatter.twig.gist
                    #        - sonata.media.formatter.twig #keep this commented unless you are using media bundle.


                    text:
                        service: sonata.formatter.text.text
                        extensions:
                            - sonata.formatter.twig.control_flow
                            - sonata.formatter.twig.gist
                    #        - sonata.media.formatter.twig


                    rawhtml:
                        service: sonata.formatter.text.raw
                        extensions:
                            - sonata.formatter.twig.control_flow
                            - sonata.formatter.twig.gist
                    #        - sonata.media.formatter.twig


                    richhtml:
                        service: sonata.formatter.text.raw
                        extensions:
                            - sonata.formatter.twig.control_flow
                            - sonata.formatter.twig.gist
                    #        - sonata.media.formatter.twig


                    twig:
                        service: sonata.formatter.text.twigengine
                        extensions: [] # Twig formatter cannot have extensions

            sonata_admin:
                security:
                    handler:              sonata.admin.security.handler.noop
                    acl_user_manager:     null
                title:                'Futurs'
                title_logo:           images/favicon.ico
                templates:
                    # default global templates
                    layout:  SonataAdminBundle::standard_layout.html.twig
                    ajax:    SonataAdminBundle::ajax_layout.html.twig
                    dashboard: SonataAdminBundle:Core:dashboard.html.twig
                dashboard:
                    blocks:
                        -
                            position: left
                            type: sonata.admin.block.admin_list
                        -
                            position: right
                            type: sonata.block.service.text
                            settings:
                                content: >
                                    <h2 style="text-align:center;">Administration du site FUTURS</h2>
            # CONFIGURATION DE VICH UPLOADER
            vich_uploader: 
                db_driver: orm 
                mappings: 
                    partenaire_dir: 
                        uri_prefix: %app.path.partenaire_dir%
                        upload_destination: %kernel.root_dir%/../web/images/partenaires
                        namer: vich_uploader.namer_uniqid
                        inject_on_load:     true
                        delete_on_update:   true
                        delete_on_remove:   true

实体:

<?php

    namespace AppBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\HttpFoundation\File\UploadedFile;
    use Symfony\Component\HttpFoundation\File\File;
    use Vich\UploaderBundle\Mapping\Annotation as Vich;

    /**
     * Partenaire
     *
     * @ORM\Table(name="partenaire")
     * @ORM\Entity(repositoryClass="AppBundle\Repository\PartenaireRepository")
     * @Vich\Uploadable
     */
    class Partenaire
    {
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

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

        /**
         * @Vich\UploadableField(mapping="partenaire_dir", fileNameProperty="logo")
         * 
         * @var File 
         */  
        private $logoFichier;

        /**
        * @ORM\Column(type="datetime")
        *
        * @var \DateTime
        */
        private $updatedAt;


        /**
         * Get id
         *
         * @return integer
         */
        public function getId()
        {
            return $this->id;
        }

        /**
         * Set logo
         *
         * @param string $logo
         *
         * @return Partenaire
         */
        public function setLogo($logo)
        {
            $this->logo = $logo;

            return $this;
        }

        /**
         * Get logo
         *
         * @return string
         */
        public function getLogo()
        {
            return $this->logo;
        }


        public function setLogoFichier(File $logo = null)
        {
            $this->logoFichier = $logo;
            if ($logo) {
                    $this->updatedAt = new \DateTime('now');
            }
            return $this;
        }

        public function getWebPath()
        {
           $val = $this->logo;
            return $val;               
        }

        /**
            * @return File
            */
        public function getLogoFichier()
        {
            return $this->logoFichier;
        }

        /**
         * Set updatedAt
         *
         * @param \DateTime $updatedAt
         *
         * @return Partenaire
         */
        public function setUpdatedAt($updatedAt)
        {
            $this->updatedAt = $updatedAt;

            return $this;
        }

        /**
         * Get updatedAt
         *
         * @return \DateTime
         */
        public function getUpdatedAt()
        {
            return $this->updatedAt;
        }
    }

PartenaireAdmin:

<?php
    namespace AppBundle\Admin;

    use Sonata\AdminBundle\Admin\AbstractAdmin;
    use Sonata\AdminBundle\Datagrid\ListMapper;
    use Sonata\AdminBundle\Datagrid\DatagridMapper;
    use Sonata\AdminBundle\Form\FormMapper;
    use Vich\UploaderBundle\Form\Type\VichImageType;
    use Ivory\CKEditorBundle\Form\Type\CKEditorType;

    class PartenaireAdmin extends AbstractAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            $image = $this->getSubject();       
            $fileFieldOptions = array('required' => false);
            if ($image && ($webPath = $image->getWebPath())) {

                $fullPath = '/images/partenaires/'.$webPath;

                // add a 'help' option containing the preview's img tag
                $fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />';
            }
            else
            {
                $fileFieldOptions['help'] = 'Ajouter une Image (4Mo max) (1100x700)';
            }

            // $container = $this->getConfigurationPool()->getContainer();
            $formMapper
            ->add('nom', 'text')
            ->add('description', CKEditorType::class,   array(
                'config' => array('toolbar' => 'full'),
                ))
            ->add('logoFichier', 'file', $fileFieldOptions);
        }

        protected function configureDatagridFilters(DatagridMapper $datagridMapper)
        {
            $datagridMapper
            ->add('nom');
        }

        protected function configureListFields(ListMapper $listMapper)
        {
            $listMapper
            ->addIdentifier('nom')
            ->add('description', 'text')
            ->add('logo','text');
        }
    }

2 个答案:

答案 0 :(得分:2)

在您的配置中,您有两次“vich_uploader”删除第一个并将正常工作

答案 1 :(得分:0)

  1. 首先要指出的是 - 你使用VichUploaderBundle。 bundle的开发人员为我们创建了名为VichImageType的FormType。因此,您应该在configureFormFields方法中的logoFichier声明中使用它:

    <prop key="hibernate.implicit_naming_strategy">org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl</prop>
  2. 关于帮助。我可以建议使用

    use Vich\UploaderBundle\Form\Type\VichImageType;
    use Vich\UploaderBundle\Templating\Helper\UploaderHelper as VichUploaderManager;
    
    class PartenaireAdmin extends AbstractAdmin
    {
    
      protected function configureFormFields(FormMapper $formMapper)
      {
        // ...
    
        ->add('logoFichier', VichImageType::class, $fileFieldOptions)
    
  3. 还有关于列表视图。至于我 - 查看图像的最简单,最快的解决方案是为图像字段创建客户模板。是的我知道,这不是正确的方法,但我只是提议......

    'help' => '<img src="'.$this->getVichUploaderManager()->asset($image, 'logoFichier').'" class="admin-preview" />'
    

    在模板name_of_your_template.html.twig中你可以放下几行:

    ->add('imageFile', VichImageType::class, [
            'template'  => 'AppBundle::Admin\..here_your_path..\name_of_your_template.html.twig',
            'required'      => false,
            'download_link' => false,
        ])