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

前端之家收集整理的这篇文章主要介绍了javascript – 使用Plupload和Symfony3抛出ValidationException时无响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
介绍:

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

Symfony v3.2.6
> OneUpUploaderBundle
> OneUpFlysystemBundle
> Plupload file uploading library jQuery UI Widget版本

注1:

请注意:此配置适用于单个和多个文件上传,但在抛出ValidationException时不会返回任何响应!

笔记2:

为了知道文件上传成功,我添加了对我的UploadListener部分的响应:

public function onUpload(PreUploadEvent $event)
{
    $file = $event->getFile();

    $response = $event->getResponse();

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

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

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

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

目标:

当抛出ValidationException时,我想收到相应的错误响应.

例:

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

问题:

我使用验证器来限制一些可上传文件.

目前 – 验证器限制的文件上传(正在抛出ValidationException).然而,在这种情况下,客户端/浏览器没有响应.

我不知道如何使Plupload和Symfony3在ValidationException之后返回客户端/浏览器.

码:

验证监听器:

<?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');
        }
    }
}@H_403_18@ 
 

带有JavaScript的Twig模板:

{% 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 %}@H_403_18@ 
 

UPDATE

添加当前代码的问题

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'));
    }
}@H_403_18@ 
 

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>@H_403_18@ 
 

题:

我失踪了什么

解决方法

对不起,以前的版本不正确.

OneupUploaderBundle捕获控制器中的异常并将其传递给error_handler服务.

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

您应该检查应用程序使用哪个错误处理程序.默认情况下,Plupload看起来像软件包设置为NoopErrorHandler,与您的异常无关.

Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler

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

errorhandler.xml

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

要获得所需形状的响应,您应该设置BlueimpErrorHandlerdefine 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'));
}@H_403_18@ 
 

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));
    }
    ...@H_403_18@

猜你在找的JavaScript相关文章