Laravel - Ajax图像上传 - 文件为空

时间:2016-09-18 09:36:30

标签: php jquery laravel-5.2

当我尝试使用ajax上传文件时,$ file为空。

我尝试过:

$ file =输入::文件('image'); $ file = $ request-> file('image');

jQuery的:

$(document).on('submit', '#update_form', function(e){
        e.preventDefault(e);
        $.ajax({
            type: "POST",
            url: '{{route('admin/users/update')}}',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                $('.error').fadeOut();
                success(data);
                load_data('{{route('admin/users/edit')}}', '{{ $user->id }}', '{{ $user->part }}');
            },
            error: function (data) {
                $('.success').fadeOut();
                errors(data);
            }
        })
    });

控制器:

public function updateUser(Request $request){

    //$file = Input::file('image');
    $file= $request->file('image');

    return \Response::json( $file );

}

路线:

    Route::post('admin/users/update', ['as' => 'admin/users/update', 'uses' => 'admin\UserController@updateUser']);

表格:

{!! Form::model($user, ['id' => 'update_form', 'files' => true]) !!}

<div class="col-md-12">

    <div class="form-group">
        {{ Form::label(trans('User image')) }}
        {!! Form::file('image', null,['class' => 'form-control', 'placeholder' => trans('Image')]) !!}
    </div>

    {{ Form::hidden('id') }}
    {{ Form::hidden('part', app('request')->input('part')) }}

    {!! Form::submit(trans('Save changes'), ['class' => 'pull-right btn btn-success submit', 'id' => 'submit' ]) !!}

</div>

{!! Form::close() !!}

Repsonse为空或:{}

响应图片:

https://gyazo.com/04e431f16237dfada40c864df96ad412

谢谢!

2 个答案:

答案 0 :(得分:0)

param是您的服务器方法参数

java.lang.String

答案 1 :(得分:0)

Laravel 6.x 终于确定了它,对我来说,它的工作方式是首先我使用jQuery通过其表单ID获取表单,然后创建一个新的FormData实例,该表单通过构造函数传递然后,如果您需要将任何内容作为键值对传递给服务器端,请使用append函数。

<form id="form_id" enctype="multipart/form-data">
        <div class="from-group">
            <label for="title">App name:</label>
            <input type="text" name="title" id ="title_id" class="form-control" placeholder="App name"><br>
        </div>
        <br>
        <div class="form-group">
            <input type="file" id="image" name="cover_image" autocomplete="off" class="form-control" />
           </div>
        <button type="button" onclick="WebApp.CategoryController.onClickAppSubmitButton()" class="btn btn-primary">Submit </button>
    </form>

var form = $("#form_id")[0];
    var formData = new FormData(form);
    formData.append('parent_id','0');
    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: url_app_post,
        method: "POST",
        contentType: false,
        processData: false,
        data: formData,
        success: function (result) {
            var data_array = $.parseJSON(result);
            if (data_array.status == "200") {
                messageHtml += WebApp.CategoryController.getAlertMessage("alert-success", data_array.message);
            } else {
                messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", data_array.message);
            }

            $(messageView).html(messageHtml);
        },
        error: function (jqXHR, exception) {
            messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger",
                WebApp.CategoryController.getjqXHRmessage(jqXHR, exception));

            $(messageView).html(messageHtml);
        }

    })

 function storeCategory(Request $request, $type){
        try{
            $fileNameToStore='no_image.jpg';
            if($request->hasFile('cover_image')){
                $fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
                $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
                $extension = $request->file('cover_image')->getClientOriginalExtension();
                $fileNameToStore=$fileName.'_'.time().'.'.$extension;
                $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);

            }
            $cat = new Category();
            $cat->title = $request->title;
            $cat->parent_id = $request->parent_id;
            $cat->cover_image=$fileNameToStore;
            $cat->user_id=auth()->user()->id;
            $cat->save();
            return json_encode(array("message"=>"This ".$type." successfully added", "status" => "200"));

        }catch(Exception $e){
            return  json_encode(array("message"=>$type." failed to insert: ".$e->getMessage(), "status" => "403"));
        }

    }