Laravel AJAX:通过 AJAX 发送文件时验证总是出错

Laravel AJAX: validation always error when sending file via AJAX

提问人:Akmal Saputra 提问时间:8/30/2022 更新时间:8/30/2022 访问量:275

问:

所以我这里有一个表格,我尝试将文件(pdf、doc、docx)发送到我的控制器

<div class="modal-body">
                {{-- alert if any error exist --}}
                <div class="alert-group-list-education mb-4"></div>
                <form method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="input-group mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Crew</label>
                        <select class="form-control col-sm-8" name="id_crew" id="id_crew_education">
                            
                        </select>
                    </div>
            
                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Instance</label>
                        <div class="col-sm-10">
                            <input name="instance_nm" type="text" class="form-control" id="instance_crew_education" placeholder="Instance" value="{{ old('instance_nm') }}">
                        </div>
                    </div>

                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label mr-3">Certificate</label>
                        <div class="col-sm-8">
                            <input type="file" class="custom-file-input" id="certificate_crew_education" name="scan_certificate">
                            <label class="custom-file-label" for="customFile">Choose Certificate</label>
                            <div class=" mt-2">
                                <span class="badge badge-primary">
                                    <small id="sh-text4" class="form-text mt-0">PDF,DOCX,DOC</small>
                                </span>
                                <small id="file-certificate-name"></small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">More Information</label>
                        <div class="col-sm-10">
                            <input name="more_information" type="text" class="form-control" id="more_info_crew_education" placeholder="More Information" value="{{ old('more_information') }}">
                        </div>
                    </div>

                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Year In</label>
                        <div class="col-sm-10">
                            <input name="year_in" type="number" class="form-control" id="year_in_crew_education" placeholder="Year In" value="{{ old('year_in') }}">
                        </div>
                    </div>

                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Year Out</label>
                        <div class="col-sm-10">
                            <input name="year_out" type="number" class="form-control" id="year_out_crew_education" placeholder="Year Out" value="{{ old('year_out') }}">
                        </div>
                    </div>
            
                    <div class="input-group mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Status</label>
                        <select class="form-control col-sm-3" name="status" id="status_crew_education">
                            <option value="ACT">ACT</option>
                            <option value="DE">DE</option>
                        </select>
                    </div>
            
                    <div class="form-group row mb-4">
                        <label for="colFormLabel" class="col-sm-2 col-form-label">Created User</label>
                        <div class="col-sm-10">
                            <input name="created_user" type="text" readonly value="{{ auth()->user()->id_login }}" class="form-control" id="created_user_crew_education" placeholder="col-form-label">
                        </div>
                    </div>
                
            </div>
            <div class="modal-footer">
                <button class="btn btn-close" data-dismiss="modal"><i class="flaticon-cancel-12"></i> Discard</button>
                <button type="submit" id="btn_store_crew_education" class="btn btn-primary">Save</button>
                </form>
                
            </div>

对于提交,我等待 $(“#btn_store_crew_education”) 被点击,这是我的 JS

$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

........

 $(document).on('click', '#btn_store_crew_education', function (e) {
        e.preventDefault()

        let crew_education_data = {
            id_crew: $('#id_crew_education').val(),
            instance_nm: $('#instance_crew_education').val(),
            scan_certificate: $('#certificate_crew_education').val(),
            more_information: $('#more_info_crew_education').val(),
            year_in: $('#year_in_crew_education').val(),
            year_out: $('#year_out_crew_education').val(),
            status: $('#status_crew_education').val(),
            created_user: $('#created_user_crew_education').val(),
        }

        $.ajax({
            type: "post",
            url: "crew-education",
            data: crew_education_data,
            success: function (response) {                
                if( response.status == 200 ) {
                    $("#addCrewEducationdModal").modal("hide");
                    Swal.fire(
                        'Success!',
                        `${response.message}`,
                        'success'
                    )
                    fetch_crew_list()
                    add_required_attribute_from_crew_master_modal_input()
                    add_required_attribute_from_crew_master_modal_edit_input()

                    // reseting form
                    $('#id_crew_education').val('')
                    $('#instance_crew_education').val('')
                    $('#certificate_crew_education').val('')
                    $('#more_info_crew_education').val('')
                    $('#year_in_crew_education').val('')
                    $('#year_out_crew_education').val('')
                    $('#status_crew_education').val('')
                    $('#created_user_crew_education').val('')
                } else {
                    $.each(response.errors, function (indexInArray, valueOfElement) { 
                        $('.alert-group-list-education').append(
                            `
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <strong>${valueOfElement}</strong>
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            `
                        )
                    });
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    });

但是每次我尝试提交 PDF、doc 或 docx 时,我总是收到来自 Laravel 的验证错误enter image description here

这是我的控制器

public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_crew' => 'required',
            'instance_nm' => 'required',
            'scan_certificate' => ['mimes:pdf,docx,doc'],
            'more_information' => 'required',
            'year_in' => 'required|numeric',
            'year_out' => 'required|numeric',
            'status' => 'required',
            'created_user' => 'required',
        ]);

        if( $validator->fails() ) {
            return response()->json([
                'status' => 400,
                'errors' => $validator->getMessageBag()
            ]);
        }
        else
        {
            $crew_education = new CrewEducation();
            $crew_education->id_crew = $request->id_crew;
            $crew_education->instance_nm = $request->instance_nm;

            if( $request->file('scan_certificate') ) {
                $crew_education->scan_certificate = $request->file('scan_certificate')->store('crew-scan-certificate');
            } 

            $crew_education->more_information = $request->more_information;
            $crew_education->year_in = $request->year_in;
            $crew_education->year_out = $request->year_out;
            $crew_education->status = $request->status;
            $crew_education->created_user = $request->created_user;


            $crew_education->save();

            return response()->json([
                'status' => 200,
                'message' => 'Crew Education Has Been Added'
            ]);
        }
    }

我不知道为什么我总是从验证器那里得到错误。

非常感谢您的任何帮助

JavaScript jQuery ajax Laravel 验证

评论


答:

0赞 blhylton 8/30/2022 #1

您需要使用 Formdata() 通过 jQuery 的 AJAX 处理程序上传文件。

而不是:

let crew_education_data = {
    id_crew: $('#id_crew_education').val(),
    instance_nm: $('#instance_crew_education').val(),
    scan_certificate: $('#certificate_crew_education').val(),
    more_information: $('#more_info_crew_education').val(),
    year_in: $('#year_in_crew_education').val(),
    year_out: $('#year_out_crew_education').val(),
    status: $('#status_crew_education').val(),
    created_user: $('#created_user_crew_education').val(),
}

你会做这样的事情:

let formdata = new FormData()
formdata.append('id_crew', $('#id_crew_education').val())
formdata.append('instance_nm', $('#instance_crew_education').val())
// Third parameter is to get the file name
formdata.append('scan_certificate', $("#certificate_crew_education")[0].files[0], $('#certificate_crew_education').val().split('\\').pop())
...

然后,在处理程序中

$.ajax({
    type: "post",
    url: "crew-education",
    data: formdata,
    contentType: false,
    processData: false,
    ...
})

当我写下所有这些代码时,所有这些代码都是一粒盐,但这应该让你指向正确的方向。就目前而言,该文件没有被上传,因此 Laravel 的验证正在将其踢回去。

评论

0赞 Akmal Saputra 8/30/2022
非常感谢,我忘记了发送文件的 FormData 对象