简体   繁体   English

如何使用带有多个文件+ symfony3的jQuery BlueImp上传来获取与每个文件对应的错误

[英]How to get errors that correspond to each file using jQuery BlueImp upload with multiple files + symfony3

INTRODUCTION 介绍

In order to upload multiple files to the server I am using: 为了将多个文件上传到我正在使用的服务器:

  1. Symfony v3.2.6 Symfony v3.2.6
  2. OneUpUploaderBundle OneUpUploaderBundle
  3. OneUpFlysystemBundle OneUpFlysystemBundle
  4. jQuery File Upload by Blueimp 由Blueimp上传的jQuery文件

NOTE 注意

Please note that: 请注意:

  1. this configuration works without a hitch when using single file uploads (chose file, upload it and then repeat from the start). 使用单个文件上传时,此配置工作顺利(选择文件,上传然后从头开始重复)。 My problem lies with multiple file uploads using same building blocks. 我的问题在于使用相同构建块的多个文件上传。
  2. I did not succeed in implementing jQuery File Upload example Basic Plus UI user interface. 我没有成功实现jQuery File Upload示例Basic Plus UI用户界面。 (Also, I did not find any relevant example on the Internet). (另外,我没有在互联网上找到任何相关的例子)。
  3. At the moment multiple file upload works just fine, though interface is "very Spartan" - it consists only of upload progress bar (common for all files) and upload button (to upload all added files) So there is practically no UI! 目前多个文件上传工作正常,虽然界面是“非常斯巴达” - 它只包括upload progress bar (所有文件通用)和upload button (上传所有添加的文件)所以几乎没有用户界面!

TARGET 目标

I would like to create multiple file upload that would be close to jQuery File Upload example Basic Plus UI , but: 我想创建多个文件上传,这将接近jQuery File Upload示例Basic Plus UI ,但是:

  • without file and image preview, 没有文件和图像预览,
  • without individual file upload option, 没有单独的文件上传选项,
  • without individual upload progress bar option. 没有单独的上传进度条选项。

PROBLEM 问题

There is no way (at least visible to me at the moment) to identify which file gets an error! 目前至少没有办法确定哪个文件出错了!

Example 1 例1

For example: I get following JSON response from the server 例如:我从服务器获得以下JSON响应

data.jqXHR.responseText = {"files":[{"error":"error.maxsize"},{"error":"error.maxsize"}]}

But at the time there was 3 uploaded files - and so - there is no information which error corresponds to which file! 但当时有3个上传的文件 - 所以 - 没有信息哪个错误对应哪个文件!

Example 2 例2

If I modify upload listener like so: 如果我像这样修改上传监听器:

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

    $response = $event->getResponse();

    $response['files'] = [
        'name'=> $file->getBaseName(),
        'type'=> $file->getType(),
        'size'=> $file->getSize(),
    ];

    return json_encode($response);
}

I then get broken response 然后我得到了破碎的回应

data.jqXHR.responseText = {"files":{"name":"php406E.tmp","type":"file","size":863329,"0":{"error":"error.maxsize"}}}

For the same 3 file upload - there should have been 2 errors, but there is only one error! 对于相同的3个文件上传 - 应该有2个错误,但只有一个错误!

Example 3 例3

I tried to use suggested code example , 我尝试使用建议的代码示例

for (k=0; k<data.files.length; k++)
{
    alert(data.files[k].name + "\n" + data.files[k].error);
}

but, sadly it did not work out... data.files[k].error got undefined on every step of the loop. 但是,遗憾的是它没有用... data.files[k].error在循环的每一步都undefined

CODE

My template with relevant javascript code 我的模板与相关的JavaScript代码

{% 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 title %}Upload nr.3 multiple files{% endblock %}

{% block content %}
    <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') }}" multiple="multiple" />
                </span>
                <button id="file-upload-start" type="button" class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start upload</span>
                </button>
            </form>
        </div>
        <div id="box-progress">
            <div id="box-progress-bar" style="width: 0%;"></div>
        </div>
        <div id="box-info">
            <p id="upload-status">Upload status...</p>
        </div>
    </div>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript" src="{{ asset('js/tmpl/tmpl.min.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';

            var GLOBAL = {};
            GLOBAL.upload_url = "{{ oneup_uploader_endpoint('gallery') }}";
            GLOBAL.item_count_all = 1;
            GLOBAL.item_count_ok = 0;
            GLOBAL.file_list = [];
            GLOBAL.file_list_ids_ok = [];

            function enableFileUploadControl()
            {
                $('input#file-upload').attr('disabled', false);
            }

            function disableFileUploadControl()
            {
                $('input#file-upload').attr('disabled', true);
            }

            $('#file-upload').on('fileuploadprocessfail', function (e, data)
            {
                //alert(data.files[data.index].error);
                //alert(data.files[index].error);

                alert(data.files[data.index].name + "\n" + data.files[data.index].error);

                /*
                var file = data.files[data.index];
                alert(file.error);
                console.log(file.error);
                */
            });

            $('#file-upload').on('click', function ()
            {
                clearUploadedFileList();
                $('#box-progress-bar').css('width', '1%');
            });

            $('#file-upload').fileupload(
                {
                    formData: {extra:1},
                    add: function (e, data)
                    {
                        var current_item_class,
                            allowedTypes = 'jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF',
                            fileName,
                            fileSize,
                            fileType,
                            js_allowed_upload_file_size;

                        fileName = data.files[0].name;
                        fileSize = data.files[0].size;
                        fileType = data.files[0].name.split('.').pop();
                        js_allowed_upload_file_size = 1048576;
                        //console.log('fileSize = '+ fileSize);

                        if (allowedTypes.indexOf(fileType) < 0)
                        {
                            $('#box-progress-bar').css('width', '0');
                            current_item_class = 'upload-item-'+ GLOBAL.item_count_all;
                            $('<div class="upload-item '+ current_item_class +'"/>').appendTo($('#box-info'));
                            $('<p/>').text(fileName).appendTo('.'+ current_item_class);
                            $('<p class="wrong-file-type"/>').text('Invalid file type').appendTo('.'+ current_item_class);

                            GLOBAL.item_count_all++;
                        }
                        /*
                        else if (fileSize > js_allowed_upload_file_size)
                        {
                            current_item_class = 'upload-item-'+ GLOBAL.item_count_all;
                            $('<div class="upload-item '+ current_item_class +'"/>').appendTo($('#box-info'));
                            $('<p/>').text(fileName).appendTo('.'+ current_item_class);
                            $('<p class="upload-error"/>').text('Max size exceeded').appendTo('.'+ current_item_class);

                            GLOBAL.item_count_all++;
                        }
                        */
                        else
                        {
                            current_item_class = 'upload-item-'+ GLOBAL.item_count_all;
                            $('<div class="upload-item '+ current_item_class +'"/>').appendTo($('#box-info'));
                            $('<p/>').text(fileName).appendTo('.'+ current_item_class);
                            if ($('.button-upload').length == 0)
                            {
                                // disabling file input
                                $('input#file-upload').attr('disabled', true);

                                $('<p class="ready-to-upload"/>').text('Ready to upload').appendTo('.'+ current_item_class);
                            }

                            //console.log('global.item_count_all = '+ GLOBAL.item_count_all);
                            GLOBAL.file_list.push(data.files[0]);
                            GLOBAL.file_list_ids_ok.push(GLOBAL.item_count_all);
                            GLOBAL.item_count_all++;
                            GLOBAL.item_count_ok++;
                        }
                    },
                    progressall: function (e, data)
                    {
                        var progress = parseInt(data.loaded / data.total * 100, 10);
                        $('#box-progress-bar').css('width', progress + '%');
                    },
                    done: function (e, data)
                    {
                        console.log('inside MAIN DONE');

                        var i,
                            k,
                            errorType,
                            message = [];

                        //console.log('data = '+ data);
                        console.log('data.jqXHR.responseText = '+ data.jqXHR.responseText);
                        console.log(data);

                        if (data.jqXHR.responseText.length > 2)
                        {
                            errorType = $.parseJSON(data.jqXHR.responseText);
                            errorType = errorType['files'][0]['error'];

                            if (errorType === "error.forbidden_mime_type")
                            {
                                message[0] = 'error';
                                message[1] = 'Forbidden file type';
                            }
                            else if (errorType === "error.mime_type_mismatch")
                            {
                                message[0] = 'error';
                                message[1] = 'Invalid mime type';
                            }
                            else if (errorType === "error.maxsize")
                            {
                                message[0] = 'error';
                                message[1] = 'Max size exceeded';
                            }
                            else if (errorType === "error.whitelist")
                            {
                                message[0] = 'error';
                                message[1] = 'Invalid file';
                            }
                        }
                        else
                        {
                            message[0] = 'all is ok';
                            message[1] = 'No error found';
                        }

                        for (k=0; k<data.files.length; k++)
                        {
                            alert(data.files[k].name + "\n" + data.files[k].error);

                            i = GLOBAL.file_list_ids_ok[k];
                            console.log(i);

                            if (message[0] === 'error')
                            {
                                $('<p class="upload-error"/>').text(message).appendTo('.upload-item-'+ i);
                            }
                            else if (message[0] === 'no error')
                            {
                                $('<p class="upload-success"/>').text(message).appendTo('.upload-item-'+ i);
                            }
                        }

                        // after all is done
                        updateUploadFileListUploadFinished();
                        enableFileUploadControl();
                        resetUploadFormCounters();

                    },
                    start: function(e, data)
                    {
                        //console.log("Upload started");
                        console.log('inside MAIN START');
                        disableFileUploadControl();
                        updateUploadFileListUploading();
                    }
                }
            );

            $('#file-upload-start').on('click', function()
            {
                $('#file-upload').fileupload('send',
                    {
                        files: GLOBAL.file_list,
                        url: GLOBAL.upload_url,
                        dataType: 'json',
                        start: function(e, data) {},
                        done: function (e, data) {}
                    }
                );
            });

            function clearUploadedFileList()
            {
                $('.upload-item').remove();
            }

            function updateUploadFileListUploading()
            {
                var i,
                    ok_item_class;

                for (i=0; i<GLOBAL.file_list_ids_ok.length; i++)
                {
                    ok_item_class = 'upload-item-'+ GLOBAL.file_list_ids_ok[i];
                    $('<p class="upload-success"/>').text('Uploading...').appendTo('.'+ ok_item_class);
                }
            }

            function updateUploadFileListUploadFinished()
            {
                var i,
                    ok_item_class;

                for (i=0; i<GLOBAL.file_list_ids_ok.length; i++)
                {
                    ok_item_class = 'upload-item-'+ GLOBAL.file_list_ids_ok[i];
                    $('<p class="upload-success"/>').text('Upload finished').appendTo('.'+ ok_item_class);
                }
            }

            function resetUploadFormCounters()
            {
                GLOBAL.item_count_all = 1;
                GLOBAL.item_count_ok = 0;
                GLOBAL.file_list = [];
                GLOBAL.file_list_ids_ok = [];
                GLOBAL.message = [];
            }
        });
    </script>
{% endblock %}

FINALLY 最后

  1. What am I missing? 我错过了什么?
  2. Am I overlooking some parameter in configuration? 我在配置中忽略了一些参数吗?
  3. Might it be a bug in jQuery File Upload by Blueimp javascript library? 可能是jQuery File Upload by Blueimp javascript库的jQuery File Upload by Blueimp的错误?

CONCLUSION 结论

Please advise. 请指教。

Thank You for your time and knowledge. 感谢您的时间和知识。

UPDATES 更新

Update 1 更新1

I have following settings in php.ini 我在php.ini有以下设置

  • post_max_size=3G 的post_max_size = 3G
  • upload_max_filesize=3G 的upload_max_filesize = 3G
  • max_file_uploads=20 max_file_uploads = 20

Update 2 更新2

So I changed my Upload listener like so: 所以我改变了我的Upload listener

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

    $response = $event->getResponse();

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

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

And now example 2 returns: 现在示例2返回:

data.jqXHR.responseText = {"files":[{"error":"none"},{"error":"error.maxsize"},{"error":"error.maxsize"}]}

I updated JavaScript part and now it is iterating through responseText and updating items with corresponding errors. 我更新了JavaScript部分,现在它正在迭代responseText并更新具有相应错误的项目。

If you see/know a better way, please comment. 如果您看到/知道更好的方式,请发表评论。

In your php.ini , do you increased the value of upload_max_filesize ? 在你的php.ini ,你是否增加了upload_max_filesize的值?

Seeing your examples, it looks like you're trying to load files larger than the size allowed by the php configuration. 看到您的示例,看起来您正在尝试加载大于php配置允许的大小的文件。

If you are in Firefox you can use the shortcut Ctrl+Shift+Q , try again to load the files and look for the request with status 500, you can see the error in the Preview tab. 如果您在Firefox中,可以使用快捷键Ctrl+Shift+Q ,再次尝试加载文件并查找状态为500的请求,您可以在“预览”选项卡中看到错误。

Example: 例: 获取ajax请求的错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM