通过jquery submit()提交表单后的Laravel文件验证;

时间:2015-06-05 06:28:14

标签: jquery laravel file-upload laravel-4 laravel-validation

当我尝试通过jquery提交表单后验证图像文件

$('#logo').submit(); 

我总是得到验证错误

The img field is required

以下是我用于验证文件的验证

$input = array('img' => Input::file('img'));
$rules = array(
        'img' => 'required',
);
// Now pass the input and rules into the validator
$validator = Validator::make($input, $rules);

// check if the validator failed -----------------------
if ($validator->fails()) {
    // get the error messages from the validator
    $messages = $validator->messages();
    // redirect our user back to the form with the errors from the validator
    print_r($messages);
}

我无法确定脚本有什么问题, 帮助我克服这个问题。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

要使用jQuery + ajax向Laravel提交文件,我遵循以下方法:

示例表单:

<form class="form-horizontal" role="form" method="POST" id="imageUpload" action="some/backend/method" enctype="multipart/form-data">
    <div class="form-group">
        <div class="alert alert-danger" style="display: none;"></div>
        <label class="col-sm-3 control-label no-padding-right"> <i class="fa fa-asterisk light-red"></i> Image</label>
        <div class="col-sm-9">
            <input type="file" name="image" class="form-control" required/>
        </div>
    </div>
</form>
  

注意:为表单设置ID。

ajax请求示例:

$.ajax({
    type: 'POST',
    data: new FormData($("#imageUpload")[0]),
    url: 'some/backend/method',
    processData: false,
    contentType: false
}).done(function (result) {
    if ($.isEmptyObject(result.error)) {
        window.location.reload();
    } else {
        var messages = '';
        for (var key in result.error) {
            if (result.error.hasOwnProperty(key)) {
                messages += result.error[key] + '<br />';
            }
        }
        $("#imageUpload .alert").html(messages).css('display', 'block');
    }
}, "json");
  

注意: processData: false&amp; contentType: false非常重要。

在后端(Laravel):

$validator = Validator::make(Input::all(), [
    'image' =>'required'
]);

if ($validator->fails()) {
    return Response::json(['error' => $validator->messages()]);
} else {
    return Response::json(['success' => true]);
}

答案 1 :(得分:0)

如果您要提交<input type="file">ajax/jquery的表单,则几乎不可能,除非您使用Jquery file uploaddropzone.js之类的内容,等等。但是你仍然可以使用XMLHttpRequest自己做一个替代方法。以下示例:

var forms = document.querySelector('form#yourFormId');

   var request = new XMLHttpRequest();

   var formDatas = new FormData(forms);
   request.open('post','upload');
   //Here "upload" is your post route
   request.send(formDatas);

   request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
       //The request was successful

     }else{

    //Request wasn't OK
}

然后你应该能够在你的控制器中叫你输入文件名:

Input::get('inputFileName')