如何在具有其他字段的简单Ajax(无FormData)中上载PDF

时间:2019-07-18 20:28:08

标签: ajax laravel laravel-5.8

我想要一张Ajax表格来上传申请人详细信息(姓名,电子邮件,号码,简历文件)。尽管文件路径将到达Controller,但作为文件请求是不可接受的。

控制器

public function store(Request $request)
{
    $rules = array(
        'Name' => 'required',
        'Email' => 'required',
        'Phone_Num' => 'required',
        'Resume' => 'required',
    );

    $error = Validator::make($request->all(), $rules);
    if ($error->fails()) {
        return Response::json(['errors' => $error->errors()->all()]);
    }

    if ($request->hasFile('Resume')) {
        $filenameWithExt = $request->file('Resume')->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extention = $request->file('Resume')->getClientOriginalExtension();
        $fileNameToStore = $filename.'_'.time().'.'.$extention;
        $path = $request->file('Resume')->storeAs('public/storage/Resume', $fileNameToStore);
    } else {
        $fileNameToStore = 'nofileavailable';
    }

    $career = array(
        'Name' => $request->Name,
        'Email' => $request->Email,
        'Phone_Num' => $request->Phone_Num,
        'Resume' => $fileNameToStore,
    );

    CareerResponses::create($career);

    return Response::json(['success' => 'Data Added Successfully']);
}

刀片

<h4 class="mb-0 mo-mb-20">Submit resume</h4><br>
<span id="form_result"></span>
<form class="form-horizontal" id="sample_form" method="POST" enctype="multipart/form-data">
    <div class="form-group row mb-3">
        <div class="col-12">
            <label for="exampleInputEmail1">Name</label>
            <input type="text" id="Name" name="Name" class="form-control" placeholder="Name" required="">
        </div>
    </div>
    <div class="form-group row mb-3">
        <div class="col-12">
            <label for="exampleInputEmail1">Email Email</label>
            <input type="text" id="Email" name="Email" class="form-control" placeholder="Email Id" required="">
        </div>
    </div>
    <div class="form-group row mb-3">
        <div class="col-12">
            <label for="exampleInputEmail1">Phone Number</label>
            <input type="text" id="Phone_Num" name="Phone_Num" class="form-control" placeholder="Phone Number"
                   required=""></div>
    </div>
    <div class="form-group row mb-3">
        <div class="col-12">
            <label for="exampleInputEmail1">Submit Resume</label>
            <input type="file" id="Resume" name="Resume" class="form-control" required="">
        </div>
    </div>
    <div class="form-group mb-0 justify-content-end row">
        <div class="col-12">
            <button class="btn btn-success btn-submit">Submit</button>
        </div>
    </div>
</form>

Ajax

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrftoken"]').attr('content')
    }
});

$('form').submit(function (e) {
    e.preventDefault();
    var name = $("input[name=Name]").val();
    var number = $("input[name=Phone_Num]").val();
    var email = $("input[name=Email]").val();
    var Resume = $("input[name=Resume]").val();

    $.ajax({
        type: 'POST',
        url: "{{ route('careers.store') }}",
        data: {Name: name, Phone_Num: number, Email: email, Resume: Resume},
        success: function (data) {
            var html = '';
            if (data.errors) {
                alert(data);
                html = '<div class="alert alert-danger">';
                for (var count = 0; count < data.errors.length; count++) {
                    html += '<p>' + data.errors[count]
                        + '</p>';
                }
                html += '</div>';
            } else {
                alert(data.success);
                html = '<div class="alert alert-success"><p>' + data.success + '</p></div>';
                $('#sample_form')[0].reset();
                $('#form_result').html(html);
            }
        }
    })
});
  

恢复变量包含发送数据后的文件路径

1 个答案:

答案 0 :(得分:0)

您正在发送恢复值,该值将始终是文件本地路径,并且无法在服务器上访问。

您可以使用FileReader并将其作为表单变量发送。

var filesSelected = document.getElementById("imageUploadfile").files;
var data = {Name: name, Phone_Num: number, Email: email}
if (filesSelected.length > 0) {
    var fileToLoad = filesSelected[0];
    var fileReader = new FileReader();
    fileReader.onload = function (fileLoadedEvent) {

        data.Resume = fileLoadedEvent.target.result;
    };
    fileReader.readAsDataURL(fileToLoad);
}
// AJAX IT

使用FormData尝试以下代码。

    // Get form
    var form = $('#sample_form')[0];

    // Create an FormData object 
    var data = new FormData(form);
    $.ajax({
        type: 'POST',
        url: "{{ route('careers.store') }}",
        enctype: 'multipart/form-data',
        data: data,
        success: function (data) {
            var html = '';
            if (data.errors) {
                alert(data);
                html = '<div class="alert alert-danger">';
                for (var count = 0; count < data.errors.length; count++) {
                    html += '<p>' + data.errors[count]
                        + '</p>';
                }
                html += '</div>';
            } else {
                alert(data.success);
                html = '<div class="alert alert-success"><p>' + data.success + '</p></div>';
                $('#sample_form')[0].reset();
                $('#form_result').html(html);
            }
        }
    })