介绍

大约两周前,我使用OneupUploaderBundle创建了有关上载的类似问题,但使用了FineUploader库。不幸的是,目前还没有答案。
同时,我尝试设置其他上传库。

我正在使用Windows 10 Pro [1](其中包括XAMPP)在PHP v7.0.8上进行开发。

  • [1] XAMPP for Windows

  • 我正在使用Symfony v3.1.5,OneupUploaderBundleBlueimp jQuery upload来将文件上传到服务器。

    在进行设置时,我遵循了OneUpUploaderBundle [2]和jQuery file upload [3],[4]的文档。
  • [2] OneupUploaderBundle documentation
  • [3] OneupUploaderBundle Blueimp example
  • [4] Blueimp jQuery file upload documentation

  • 问题

    我想将文件上传到某个目录,然后检查其mime type并验证是否允许上传文件mime类型,然后将其移动到自定义目录(可以在文件之间更改),最后我想保留文件路径和文件数据库名称。

    文件上传正常,文件上传到oneup_uploader_endpoint('gallery')。甚至自定义文件Namer都可以工作,并允许上传到自定义目录。

    但是,监听器不称为(上传监听器和验证),而是显示在Symfony Profiler事件部分的Not Called Listeners中!

    不幸的是,我想使用Post_Persist事件将有关文件的信息保存到数据库。 OneupUploaderBundle events

    代码

    我的services.yml
    services:
        app.upload_listener:
            class: AppBundle\EventListener\UploadListener
            arguments: ["@doctrine.orm.entity_manager"]
            tags:
                - { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onUpload }
                - { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onPostUpload }
    
        app.upload_unique_namer:
            class: AppBundle\Uploader\Naming\UploadUniqueNamer
            arguments: ["@session"]
    

    我的自定义命名器
    <?php
    
    namespace AppBundle\Uploader\Naming;
    
    use Oneup\UploaderBundle\Uploader\File\FileInterface;
    use Oneup\UploaderBundle\Uploader\Naming\NamerInterface;
    use Symfony\Component\HttpFoundation\Session\Session;
    
    class UploadUniqueNamer implements NamerInterface
    {
        private $session;
    
        public function __construct(Session $session)
        {
            $this->session = $session;
        }
    
        /**
         * Creates a user directory name for the file being uploaded.
         *
         * @param FileInterface $file
         * @return string The directory name.
         */
        public function name(FileInterface $file)
        {
            $upload_files_path = $this->session->get('upload_files_path');
            $unique_name = uniqid();
    
            return sprintf('%s/%s_%s',
                $upload_files_path,
                $unique_name,
                $file->getClientOriginalName()
            );
        }
    }
    

    我的config.yml
    oneup_uploader:
        mappings:
            gallery:
                frontend: blueimp
                enable_progress: true
                namer: app.upload_unique_namer
                use_orphanage: false
                allowed_mimetypes: [image/png, image/jpg, image/jpeg, image/gif]
                max_size: 200M
    

    我的上传监听器:
    <?php
    
    namespace AppBundle\EventListener;
    
    use Oneup\UploaderBundle\Event\PreUploadEvent;
    use Oneup\UploaderBundle\Event\PostUploadEvent;
    use Oneup\UploaderBundle\Event\PostPersistEvent;
    use Doctrine\ORM\EntityManager;
    use AppBundle\Entity\Product;
    
    class UploadListener
    {
        /**
         * @var EntityManager
         */
        private $entityManager;
    
        //protected $originalName;
    
        public function __construct(EntityManager $entityManager)
        {
            $this->entityManager = $entityManager;
        }
    
        public function onUpload(PostPersistEvent $event)
        {
            $file = $event->getFile();
            $this->originalName = $file->getClientOriginalName();
        }
    
        public function onPostUpload(PostPersistEvent $event)
        {
            $file = $event->getFile();
    
            $object = new Product();
            $object->setName($file->getClientOriginalName());
            //$object->setName($file->getPathName());
    
            $this->entityManager->persist($object);
            $this->entityManager->flush();
        }
    }
    

    upload.html.twig
    {% extends 'base.html.twig' %}
    
    {% block stylesheets %}
        {{ parent() }}
        <link rel="stylesheet" type="text/css" href="{{ asset('css/blueimp/jquery.fileupload.css') }}" />
        <link rel="stylesheet" type="text/css" href="{{ asset('css/bootstrap/bootstrap.css') }}" />
        <link rel="stylesheet" type="text/css" href="{{ asset('css/bootstrap/bootstrap-theme.css') }}" />
    {% endblock %}
    
    {% block content %}
        <div id="box-list" class="clearfix">
            Go to: <a href="{{ path('product_list') }}">Product list</a>
        </div>
        <div id="box-upload">
            <div id="box-file-upload">
                <form method="post" enctype="multipart/form-data">
                    <span class="btn btn-success fileinput-button">
                        <i class="glyphicon glyphicon-plus"></i>
                        <span>&nbsp;Choose files...</span>
                        <input id="file-upload" type="file" name="files[]" data-url="{{ oneup_uploader_endpoint('gallery') }}" />
                    </span>
                </form>
            </div>
            <div id="box-progress">
                <div id="box-progress-bar" style="width: 0%;"></div>
            </div>
            <div id="box-info">
                <p>Upload status...</p>
            </div>
        </div>
    {% endblock %}
    
    {% block javascripts %}
        {{ parent() }}
        <script type="text/javascript" src="{{ asset('js/jquery-3.1.0.js') }}"></script>
        <script type="text/javascript" src="{{ asset('js/blueimp/jquery.ui.widget.js') }}"></script>
        <script type="text/javascript" src="{{ asset('js/blueimp/jquery.iframe-transport.js') }}"></script>
        <script type="text/javascript" src="{{ asset('js/blueimp/jquery.fileupload.js') }}"></script>
        <script type="text/javascript">
            $(function()
            {
                'use strict';
                $('#file-upload').on('click', function ()
                {
                    $('#box-progress-bar').css('width', '1%');
                });
    
                $('#file-upload').on("fileuploadprocessfail", function(e, data)
                {
                    var file = data.files[data.index];
                    alert(file.error);
                    console.log(file.error);
                });
    
                $('#file-upload').fileupload({
                    dataType: 'json',
                    add: function (e, data)
                    {
                        var fileName = data.files[0].name;
                        var fileType = data.files[0].name.split('.').pop();
                        var allowedTypes = 'jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF';
                        if (allowedTypes.indexOf(fileType) < 0)
                        {
                            $('#box-progress-bar').css('width', '0');
                            $('<p/>').text(fileName).appendTo($('#box-info'));
                            $('<p class="wrong-file-type"/>').text('Invalid file type').appendTo($('#box-info'));
                            return false;
                        }
                        else
                        {
                            $('<p/>').text(fileName).appendTo($('#box-info'));
                            if ($('.button-upload').length == 0)
                            {
                                // disabling file input
                                $('input#file-upload').attr('disabled', true);
    
                                data.context = $('<button class="button-upload btn btn-primary start"/>').text('Upload')
                                        .appendTo($('#box-info'))
                                        .click(function ()
                                        {
                                            data.context = $('<p class="upload-success"/>').text('Uploading...').replaceAll($(this));
                                            ($('.button-cancel')).remove();
                                            data.submit();
                                        });
                                $('<button class="button-cancel btn btn-warning cancel" />').text('Cancel')
                                        .appendTo($('#box-info'))
                                        .click(function ()
                                        {
                                            $('#box-progress-bar').css('width', '0');
                                            //console.log('testing');
                                            var message = 'Upload canceled';
                                            ($('.button-upload')).remove();
                                            ($('.button-cancel')).remove();
                                            $('<p class="wrong-file-type"/>').text(message).appendTo($('#box-info'));
                                            // enabling file input
                                            $('input#file-upload').attr('disabled', false);
                                        });
                            }
                        }
                    },
                    progressall: function (e, data)
                    {
                        var progress = parseInt(data.loaded / data.total * 100, 10);
                        $('#box-progress-bar').css('width', progress + '%');
                    },
                    done: function (e, data)
                    {
                        data.context.text('Upload finished.');
                        // enabling file input
                        $('input#file-upload').attr('disabled', false);
                    }
                });
            });
        </script>
    {% endblock %}
    

    更新
  • 添加了有关开发环境的注释。
  • 与Symfony v2.8.8尝试了相同的代码,遗憾的是未调用UploadListener。
  • 编辑了services.yml,删除了(我认为),现在不再需要(重复-在OneupUploaderBundle中提供),我在尝试使其生效时添加了该验证...

    结论

    请指教。

    感谢您的时间和知识。

    最佳答案

    只是听正确的事件。
    事件交换包含映射的名称,以便您可以对此映射实现一种不会影响其他逻辑的特定逻辑。

    此格式的事件。

    oneup_uploader.post_upload.{mapping}
    

    在你的情况下,它会给
    oneup_uploader.post_upload.gallery
    

    欲了解更多信息,请阅读
    https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/events.md

  • 10-01 01:36