jQuery.FileUpload HTTP 响应错误

jQuery.FileUpload HTTP Response errors

我正在使用 blueimp 的 jQuery.fileUpload 组件构建使用 Laravel 5 的应用程序的一部分。表单本身按预期工作,但我很难处理服务器端验证:

Laravel 的请求验证处理 ajax 请求的后端验证,当验证失败时,将使用 HTTP 422 代码发送响应。

主要问题是 blueimp 的 jQuery.fileUpload 不解析包含验证消息的 file (json) 数组 (doc. link)。相反,它只是使用 HTTP 422 代码的标准描述。

你们知道覆盖它的方法吗?如何从验证中手动解析 json return?或者有没有办法使 Laravel return HTTP 200 即使验证失败?

这是一些代码:

Laravel的请求class:

    class UploadRequest extends Request {

        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }

        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            Log::info("Request de upload");
            return [
                'file' => 'required|max:1200'
            ];
        }
    }

这是我的 jQuery.fileUpload 初始化脚本:

$(function () {
    'use strict';
    var jupload = $('#fileupload');
    jupload.fileupload({
        url: window.location
    });

    // from 
    if (typeof existingfiles !== 'undefined'){
        jupload.fileupload('option', 'done').call(jupload, $.Event('done'), {result: existingfiles});
    };
});

提前致谢, Peixoto.

几天前我遇到了同样的问题...如果您查看每个回调中可用的 data 对象,您会发现它在另一个对象中,jqXHR (毕竟我们只处理一个 jQuery AJAX 调用),它本身有另一个对象 responseJSON,带有一个包含您要查找的错误的数组。

来自官方blueimp docs:

"The send method returns a jqXHR object, that allows to bind callbacks to the ajax file upload request(s):"

var jqXHR = $('#fileupload').fileupload('send', {files: filesList})
.success(function (result, textStatus, jqXHR) {/* ... */})
.error(function (jqXHR, textStatus, errorThrown) {/* ... */})
.complete(function (result, textStatus, jqXHR) {/* ... */});

所以现在,您可以做类似...

$('#fileupload').fileupload({
    fail: function (e, data) {
        var errors = data.jqXHR.responseJSON;
        $.each(errors, function (key, value) {
            alert(value);
        });
    }
});

或者更合适:

var jqXHR = data.submit()
        .success(function (result, textStatus, jqXHR) {/* ... */})
        .error(function (jqXHR, textStatus, errorThrown) {
            console.log(data);
            var errors = jqXHR.responseJSON;
            $.each(errors, function (key, value) {
                alert(value);
            });
        })
        .complete(function (result, textStatus, jqXHR) {/* ... */});