当我尝试通过ajax上传图像时,Laravel出错

时间:2022-08-09 20:16:11

simply i can upload image with below codes. but after try to use the controller's action to upload image by ajax i get error:

只需我可以使用以下代码上传图像。但在尝试使用控制器的动作通过ajax上传图像后,我得到错误:

Error:

Call to a member function move()

My codes:

{!! Form::open(['url' => 'registerToBuyCard', 'id' => 'register_to_buy_card','style'=>'text-align:left;','enctype'=>"multipart/form-data"]) !!}

<div class="form-group">
    <label for="passport">Passport Image</label>
    {!! Form::file('passport') !!}
</div>

<button type="submit" class="btn btn-default">Submit</button>
</fieldset>
{!! Form::close() !!}

Ajax:

$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var $this = $(this);
    var url = $this.attr('action');

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: $this.serialize(),
        success: function (data) {
            if (data.code == '1') {
                alert('thanks');
            } else
                apprise("<span style='font-size:11px;font-family: Tahoma'>" + data.message + "</span>");
        },
        error: function (data) {
            apprise("<span style='font-size:11px;font-family: Tahoma'>" + data.message + "</span>");
        }
    });
});

Controller action:

public function registerToBuyCard(Request $request)
{
    $file = $request->file('passport');
    $filename = $this->upload_image($file);
}
public function upload_image($filename)
{
    $destinationPath = base_path() . '/upload/';
    if ($filename->move($destinationPath, $filename))
        return $filename;
    else
        return false;
}

1 个解决方案

#1


0  

Problem Solved:

$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var $this = $(this);
    var url = $this.attr('action');
    var formData = new FormData(this);
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: formData,
        contentType:false,
        processData:false,
        success: function (data) {

        },
        error: function (data) {

        }
    });
});

#1


0  

Problem Solved:

$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var $this = $(this);
    var url = $this.attr('action');
    var formData = new FormData(this);
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: formData,
        contentType:false,
        processData:false,
        success: function (data) {

        },
        error: function (data) {

        }
    });
});