使用AJAX进行文件上传验证

时间:2014-07-06 19:28:58

标签: jquery ajax laravel laravel-4

我正在尝试对文件上传进行验证。我正在使用AJAX,但验证过程中存在问题。

jQuery('#form-docs').submit(function()
{
    var url = $(this).attr("action");
    jQuery.ajax({
        url: url,
        type: "post",
        data: jQuery('#form-docs').serialize(),
        datatype: "json",
        beforeSend: function()
        {
            jQuery('#ajax-loading').show();
            jQuery(".validation-error-inline").hide();
        }
    })
            .done(function(data)
            {
                $('#validation-div').empty()
                if (data.validation_failed === 1)
                {
                    var arr = data.errors;

                   alert(arr);
                }
                else {
                    window.location = data.redirect_to;
                }
            })
    return false;
});

控制器

 if ((Input::file('owner_cert_doc') != NULL) || (Input::file('sgs_doc') != NULL) || (Input::file('tpl_doc') != NULL) || (Input::file('kasko_doc') != NULL) || (Input::file('drive_permis_doc') != NULL)) {
            $car_id = Input::get('id_value');
            $id = DB::select('select id from insur_docs where car_id=?', array($car_id));
            $id_insert = DB::select('select id from insurdocs_inserts where car_id=?', array($car_id));
            $options = ['gs' => ['Content-Type' => 'text/plain']];
            $ctx = stream_context_create($options);
            //ownership certificate documentations
            $random_owner = str_random(5);
            if (Input::hasFile('owner_cert_doc')) {
                $owner_input = Input::get('owner_cert_doc');
                $owner_cert_doc = $_FILES['owner_cert_doc']['name'];
                if (false == rename($_FILES['owner_cert_doc']['tmp_name'], 'gs://docs_upload/' .
                                $random_owner . '_' . $owner_cert_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
 $car = InsurDoc::find($id[0]->id);
            if (Input::hasFile('owner_cert_doc')) {
                $car->owner_cert_doc = 'gs://docs_upload/' . $random_owner . '_' . $owner_cert_doc;
            }
$car->save();

            return Redirect::to('car/' . $car_id);
        } else {        
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => Lang::get('messages.invalid_upload'),
                );
                return Response::json($response_values);   
        }

问题是当点击提交时没有任何反应。控制台显示:"Post 400 (bad request) 相反,如果用dd替换else('error');它显示“错误”。

1 个答案:

答案 0 :(得分:0)

Darin Dimitrov的评论是正确的,为此你可以使用http://www.plupload.com/或类似的插件来上传AJAX文件。他们的文档中有前端和后端的示例。很简单:)