使用 Plupload 和 Symfony3 抛出 ValidationException 时无响应

No response when ValidationException is thrown using Plupload and Symfony3

简介:

为了将多个文件上传到我正在使用的服务器:

  1. Symfony v3.2.6
  2. OneUpUploaderBundle
  3. OneUpFlysystemBundle
  4. Plupload file uploading library jQuery UI Widget 版本

注 1:

请注意:此配置适用于单个和多个文件上传,但它 return 任何 responseValidationException被抛出!

注 2:

为了知道文件上传成功完成,我在 UploadListener:

的一部分添加了响应
public function onUpload(PreUploadEvent $event)
{
    $file = $event->getFile();

    $response = $event->getResponse();

    $message = [
        'error' => 'none'
    ];

    $response->addToOffset($message, array('files'));
}

它给出以下响应(如果文件上传没有错误

response: {"files":[{"error": "none"}]}

目标:

我想在抛出 ValidationException 时收到带有相应错误的 response

示例:

response: {"files":[{"error": "error code"}]}

问题:

我正在使用验证器来限制一些可上传的文件。

目前 - validator 限制的文件 上传(ValidationException 被抛出)。但是这次没有 response 发送到 client/browser!

我不知道如何在 ValidationException 到 client/browser 之后使 PluploadSymfony3 return 错误。

代码:

验证侦听器:

<?php

namespace AppBundle\EventListener;

use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Exception\ValidationException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class AllowedMimeTypeValidationListener
{
    /**
     * @var Container
     */
    private $container;

    private $file_extension_array = [];
    private $file_type_array = [];
    private $banned_files = [];

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function onValidate(ValidationEvent $event)
    {
        $ultra_helpers = $this->container->get('app.ultra_helpers');
        $ultra_text = $this->container->get('app.ultra_text');

        array_push($this->file_extension_array, '.gif');
        array_push($this->file_extension_array, '.jpg');
        array_push($this->file_extension_array, '.jpeg');
        array_push($this->file_extension_array, '.png');
        array_push($this->file_extension_array, '.zip');
        array_push($this->file_extension_array, '.7z');
        array_push($this->file_extension_array, '.pdf');
        array_push($this->file_extension_array, '.bin');
        array_push($this->file_extension_array, '.txt');

        array_push($this->file_type_array, 'image/gif');
        array_push($this->file_type_array, 'image/jpg');
        array_push($this->file_type_array, 'image/jpeg');
        array_push($this->file_type_array, 'image/png');
        array_push($this->file_type_array, 'application/zip');
        array_push($this->file_type_array, 'application/x-7z-compressed');
        array_push($this->file_type_array, 'application/pdf');
        array_push($this->file_type_array, 'application/octet-stream');
        array_push($this->file_type_array, 'text/plain');

        array_push($this->banned_files, 'do_not_allow_me_1.txt');
        array_push($this->banned_files, 'do_not_allow_me_2.txt');
        array_push($this->banned_files, 'do_not_allow_me_3.txt');

        $file = $event->getFile();
        $file_extension = '.'. $file->getExtension();
        $file_mime_type = $file->getMimeType();
        $full_file_name = $file->getClientOriginalName()

        if (in_array($full_file_name, $this->banned_files))
        {
            throw new ValidationException('error.file_exists');
        }

        // Is file mime type the same as extension mime type
        $mime_type_position = array_search($file_extension, $this->file_extension_array);
        if ($mime_type_position !== false)
        {
            $mime_type_by_extension = $this->file_type_array[$mime_type_position];

            if ($mime_type_by_extension !== $file_mime_type)
            {
                throw new ValidationException('error.mime_type_mismatch');
            }
        }

        // Is file type not in activated file type array
        if (!in_array($file_mime_type, $this->file_type_array))
        {
            throw new ValidationException('error.forbidden_mime_type');
        }
    }
}

Twig 模板 JavaScript:

{% extends 'base.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.css') }}" />
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css') }}" media="screen" />
{% endblock %}

{% block content %}
    <div id="box-upload">
        <div id="uploader">
            <p>Your browser doesn't have HTML5 support.</p>
        </div>
    </div>
{% endblock %}

{% block javascripts %}
    <script type="text/javascript" src="{{ asset('js/browserplus/browserplus.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/plupload.full.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/jquery-2.2.4.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/jquery.ui.plupload/jquery.ui.plupload.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/i18n/lv.js') }}"></script>
    <script type="text/javascript">
        'use strict';

        $(function()
        {
            var uploader;

            uploader = $("#uploader");

            uploader.plupload(
            {
                // General settings
                runtimes: 'html5',
                url: "{{ oneup_uploader_endpoint('gallery') }}",
                multi_selection: true,

                // Maximum file size
                max_file_size: '5mb',

                chunk_size: '5mb',

                // Specify what files to browse for
                filters: [
                    {title: "Binary files", extensions: "bin"},
                    {title: "Image files", extensions: "gif,jpg,jpeg,png"},
                    {title: "Media files", extensions: "avi"},
                    {title: "Pdf files", extensions: "pdf"},
                    {title: "Text files", extensions: "txt"},
                    {title: "Zip files", extensions: "zip,7z"}
                ],

                // Rename files by clicking on their titles
                rename: true,

                // Sort files
                sortable: true,

                // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
                dragdrop: true,

                // Views to activate
                views: {
                    list: true,
                    thumbs: false, // Show thumbs
                    active: 'list'
                }
            });

            var $uploader = uploader.plupload('getUploader');

            // Add Clear Button
            var $button = $("<button>"+ plupload.translate("Clear list") + "</button>").button({icons: {primary: "ui-icon-trash"}}).button("disable").appendTo('.plupload_buttons');

            // Clear Button Action
            $button.click(function()
            {
                removeErrorMessages();
                $uploader.splice();
                $(".plupload_filelist_content").html('');
                $button.button("disable");
                return true;
            });

            // Clear Button Toggle Enabled
            $uploader.bind('QueueChanged', function ()
            {
                if ($uploader.files.length > 0)
                {
                    $button.button("enable");
                }
                else
                {
                    $button.button("disable");
                }
            });

            // Clear Button Toggle Hidden
            $uploader.bind('StateChanged', function ()
            {
                if ($uploader.state === plupload.STARTED)
                {
                    $button.hide();
                }
                else
                {
                    $button.show();
                }
            });

            // Clear Button Toggle Hidden
            $uploader.bind('Browse', function ()
            {
                removeErrorMessages();
                $uploader.splice();
            });

            $uploader.bind('FileUploaded', function(up, file, info)
            {
                var response;
                response = jQuery.parseJSON(info.response);

                console.log("-- next is response --");
                console.log(response);

                up.trigger("error", {message: "Fails: "+ file.name +" jau atrodas šajā mapē!<br> Augšupielādējamais fails <i>netika</i> saglabāts!", code: 12345, details: "Testing errors"});
                $("#"+ file.id).addClass("duplicateFile");
            });

            function removeErrorMessages()
            {
                $(".ui-state-error").remove();
            }
        });
    </script>
{% endblock %}

更新

将当前代码添加到问题

PluploadErrorHandler.php

<?php

namespace Oneup\UploaderBundle\Uploader\ErrorHandler;

use Exception;
use Oneup\UploaderBundle\Uploader\Response\AbstractResponse;

class PluploadErrorHandler implements ErrorHandlerInterface
{
    public function addException(AbstractResponse $response, Exception $exception)
    {
        $message = $exception->getMessage();
        $response->addToOffset(array('error' => $message), array('files'));
    }
}

errorhandler.xml

<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter>
        <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter>
        <parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter>
        <parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter>
    </parameters>

    <services>
        <service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false">
            <argument type="service" id="translator"/>
        </service>
        <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" />
        <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" />
        <service id="oneup_uploader.error_handler.fineuploader" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.uploadify" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
        <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" />
    </services>

</container>

问题:

我错过了什么?

抱歉之前的版本不正确。

OneupUploaderBundle 捕获控制器中的异常并将它们传递给 error_handler 服务。

class PluploadController extends AbstractChunkedController
{
    public function upload()
    {
        ...
        foreach ($files as $file) {
            try {
                $chunked ?
                    $this->handleChunkedUpload($file, $response, $request) :
                    $this->handleUpload($file, $response, $request)
                ;
            } catch (UploadException $e) {
                $this->errorHandler->addException($response, $e);
            }
        }
        return $this->createSupportedJsonResponse($response->assemble());
    }

您应该检查您的应用程序使用了哪个错误处理程序。看起来默认情况下 Plupload 捆绑设置 NoopErrorHandler 对你的例外没有任何作用。

Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler

public function addException(AbstractResponse $response, Exception $exception)
{
    // noop
}

errorhandler.xml

 <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />

要获得所需形状的响应,您应该设置 BlueimpErrorHandler or to define a custom handler

Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler

public function addException(AbstractResponse $response, Exception $exception)
{
    $message = $this->translator->trans($exception->getMessage(), array(), 'OneupUploaderBundle');
    $response->addToOffset(array('error' => $message), array('files'));
}

OT: 以这种方式在验证器中使用异常会给用户带来不好的体验。用户应该看到上传文件的所有错误,而不仅仅是第一个。您应该收集所有错误,然后抛出异常。例如:

    ...

    if (in_array($full_file_name, $this->banned_files))
    {
        throw new ValidationException('error.file_exists');
    }

    $errors = [];

    // Is file mime type the same as extension mime type
    $mime_type_position = array_search($file_extension, $this->file_extension_array);
    if ($mime_type_position !== false)
    {
        $mime_type_by_extension = $this->file_type_array[$mime_type_position];

        if ($mime_type_by_extension !== $file_mime_type)
        {
            $errors[] = 'error.mime_type_mismatch';
        }
    }

    // Is file type not in activated file type array
    if (!in_array($file_mime_type, $this->file_type_array))
    {
        $errors[] = 'error.forbidden_mime_type';
    }

    if (empty($errors)) {
        throw new ValidationException(implode(', ', $errors));
    }
    ...